这是代码
static BackgroundWorker worker = new BackgroundWorker();
static void Main(string[] args)
{
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync();
Console.ReadLine();
}
static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine(e.Result);
}
public static async void worker_DoWork(object sender, DoWorkEventArgs e)
{
var client = new HttpClient();
string httpResult = await client.GetStringAsync("http://ozgurakpinar.net/androidserver.aspx?param=accenture2");
e.Result = httpResult;
}
它在GetStringAsync行中永远等待。但是当我使用线程而不是BackgroundWorker时它可以工作。
答案 0 :(得分:3)
你的误解:
async void
会立即返回,导致BackgroundWorker
认为工作已完成。等待时BackgroundWorker
已过时。删除所有这些。BackgroundWorker
在控制台应用程序中毫无意义。它是为UI设计的组件。当你扔掉所有不需要的东西时,它实际上非常简单:
static void Main(string[] args)
{
Console.ReadLine(worker_DoWork().Result); //intentionally blocking here
}
static async Task<string> worker_DoWork()
{
var client = new HttpClient();
string httpResult = await client.GetStringAsync("http://ozgurakpinar.net/androidserver.aspx?param=accenture2");
return httpResult;
}
异步和线程是危险的工具。在需要时使用,而不是默认使用。