等待多个任务

时间:2015-07-17 19:32:05

标签: c# multithreading task

我有以下代码:

private async void buttonStart_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
    Bot b = new Bot(_names);
    var result = await b.Start(false, true, false);
    MessageBox.Show("Done");
}

public async Task<bool> Start(bool instagram, bool twitter, bool xbox)
{
    if (twitter)
    {
        Twitter t = new Twitter(Names);
        await t.CheckNames();
    }
    return true;
}

public Task CheckNames()
{
    List<Task> tasks = new List<Task>();
    foreach (Name name in Names)
    {
        tasks.Add(Task.Factory.StartNew(async () =>
        {
            TwitterResponse result = await Check(name);
            MessageBox.Show(result.msg);
        }));
    }
    return Task.WhenAll(tasks);
}

public async Task<TwitterResponse> Check(Name name)
{
    HttpClient http = new HttpClient();
    HttpResponseMessage response = await http.GetAsync(string.Format("https://twitter.com/users/username_available?username={0}", name.Value));
    string html = response.Content.ReadAsStringAsync().Result;
    TwitterResponse result = new JavaScriptSerializer().Deserialize<TwitterResponse>(html);
    return result;
}

但是,在任何任务完成之前,我似乎总是MessageBox"Done"

我做错了什么,如何在获得messagebox之前确保所有任务真正完成?

1 个答案:

答案 0 :(得分:3)

问题是行tasks.Add(Task.Factory.StartNew(async () =>you should almost never be using Task.Factory.StartNew而是使用Task.Run(

StartNew返回的对象是Task<Task>,这意味着它不会等待内部任务完成。在将.Unwrap()添加到集合之前,您必须在StartNew的输出上调用Task.Run(,或者更好地使用tasks.Add(Task.Run(async () => { TwitterResponse result = await Check(name); MessageBox.Show(result.msg); }));

Func<Task>

其中包含一个 <div id="hover-example"> <div id="img-holder"> </div> </div> 的重载并将为您解开内部任务。