Koborl
Koborl

Reputation: 235

C# Update UI After thread Completion

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();
}

So the problem I am currently having is that I'm blocking the UI thread with the webRequest/Response.

I'm guessing what i want to do is in each iteration of the for loop create and modify the button (including the background image) on another thread.

And when the thread is complete have some sort of callback to update the UI?

Also i'll probably need some way of returning the button created on the new thread to the main thread to update the UI with?

I'm a beginner to c# and have not really touched any multi-threading in the past, would this be the way to go about it, or am i thinking about this all wrong.

Upvotes: 2

Views: 687

Answers (1)

Andrei Tătar
Andrei Tătar

Reputation: 8295

I would use async/await and WebClient to handle this

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();
}));

Upvotes: 6

Related Questions