线程完成后C#更新UI

标签 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# 的初学者,过去没有真正接触过任何多线程,这是解决问题的方法吗, 还是我想的全错了。

最佳答案

我会使用 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();
}));

关于线程完成后C#更新UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29793410/

相关文章:

c# - 使用 IronPython 控制 C# Winforms GUI

multithreading - Spark/EMR能否从s3多线程读取数据

c# 使用 xml 文件更改按钮和文本框颜色

c# - 主窗体关闭时不调用 FormClosed 事件

c# - 在主应用程序崩溃后终止另一个进程

java - 如何在不关闭 Executor 的情况下等待 ThreadPoolExecutor 中的所有任务完成?

multithreading - 如果其他线程只读取共享数据,OpenMP 是否需要原子写入?

c# - 使用偶尔为空属性的 LINQ SequenceEqual 扩展方法

c# - 在azure sdk Fluent中使用身份验证 token

c# - 将存储在对象中的 Enum 数据绑定(bind)到 Winforms ComboBox 中?