线程完成后,C#更新UI

时间:2015-04-22 09:35:43

标签: c# multithreading winforms user-interface

for (int i = 0; i < someList.length;i++){
    Button button = new Button();
    // Modify some button attributes height,width etc

    var request = WebRequest.Create(current.thumbnail);
    var response = request.GetResponse();
    var stream = response.GetResponseStream();
    button.BackgroundImage = Image.FromStream(stream);
    stream.Close();

    // and then i have these UI components that need updating (imagePanel is a FlowLayoutPanel)
    imagePanel.Controls.Add(button);
    imagePanel.Refresh();
    progBar.PerformStep();
}

所以我目前遇到的问题是我用webRequest / Response阻止了UI线程。

我猜想我要做的是在for循环的每次迭代中创建并修改另一个按钮(包括背景图像) 线程。

当线程完成时有某种回调来更新UI?

另外我可能需要某种方法将新线程上创建的按钮返回到主线程来更新UI?

我是c#的初学者,并且过去没有真正触及任何多线程,这是否可以解决这个问题, 或者我认为这一切都错了。

1 个答案:

答案 0 :(得分:6)

我会使用async/await和WebClient来处理这个

await Task.WhenAll(someList.Select(async i =>
{
    var button = new Button();
    // Modify some button attributes height,width etc

    using (var wc = new WebClient())
    using (var stream = new MemoryStream(await wc.DownloadDataTaskAsync(current.thumbnail)))
    {
        button.BackgroundImage = Image.FromStream(stream);
    }

    // and then i have these UI components that need updating (imagePanel is a FlowLayoutPanel)
    imagePanel.Controls.Add(button);
    imagePanel.Refresh();
    progBar.PerformStep();
}));