【发布时间】:2017-12-22 04:43:03
【问题描述】:
我的问题是我想执行一些操作,例如从某个 URL 获取数据(格式为字符串)。我想运行这个过程是后台。每当用户需要此操作时,我都必须调用此操作。就像用户单击为此操作指定的按钮一样,它应该执行该功能并向该用户提供结果。问题是当执行此程序时,不应中断其他程序。我想运行这种异步方式。我想返回从 URL 下载的结果 这是我使用线程的解决方案
namespace xyz
{
public class newWinForm : Form
{
SomeClass someClass = new SomeClass();
public newWinForm()
{
Thread backgroundThread = new Thread(DoWork);
backgroundThread.IsBackground = true;
backgroundThread.Start();
}
void DoWork()
{
try
{
Console.WriteLine("Doing some work...");
using(WebClient cl = new WebClient())
{
string result = cl.DownloadString("http://www.......com");
}
Thread.Sleep(1000);
}
finally
{
Console.WriteLine("This should be always executed");
}
}
private void getDataFrmUrlButton_Click(object sender, EventArgs e)
{
Thread backgroundThread = new Thread(DoWork);
backgroundThread.IsBackground = true;
backgroundThread.Start();
}
}
【问题讨论】:
标签: c# multithreading background-task background-thread