C#线程完成后更新UI for(int i=0;i
因此,我目前遇到的问题是,我用webRequest/Response阻塞了UI线程 我猜我想做的是在for循环的每次迭代中在另一个循环上创建和修改按钮(包括背景图像) 线 当线程完成时,是否有某种回调来更新UI 另外,我可能需要某种方法将在新线程上创建的按钮返回到主线程,以更新UI 我是c#的初学者,在过去没有真正接触过任何多线程,这会是解决这个问题的方法吗, 还是我想的全错了。我会使用和WebClient来处理这个问题C#线程完成后更新UI for(int i=0;i,c#,multithreading,winforms,user-interface,C#,Multithreading,Winforms,User Interface,因此,我目前遇到的问题是,我用webRequest/Response阻塞了UI线程 我猜我想做的是在for循环的每次迭代中在另一个循环上创建和修改按钮(包括背景图像) 线 当线程完成时,是否有某种回调来更新UI 另外,我可能需要某种方法将在新线程上创建的按钮返回到主线程,以更新UI 我是c#的初学者,在过去没有真正接触过任何多线程,这会是解决这个问题的方法吗, 还是我想的全错了。我会使用和WebClient来处理这个问题 for (int i = 0; i < someList.lengt
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();
}
不要自己使用线程。BackgroundWorker是一种更好的方法,它在最后包括一个回调,以便UI线程处理事情。如果确实需要使用线程,则可以在需要时使用表单的
Invoke()
方法调用UI线程中的代码。但是先试试BGWorker也看看谢谢,这些文件帮了大忙。
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();
}));