Kob*_*orl 2 c# user-interface multithreading winforms
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();
}
Run Code Online (Sandbox Code Playgroud)
所以我目前遇到的问题是我使用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();
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
466 次 |
| 最近记录: |