2
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.

3
  • 3
    Don't use threads yourself. BackgroundWorker is a lot better way and it includes a callback in the end for UI thread to handle things. If you really need to use threads, you can use Form's Invoke() method to call code in the UI thread when needed. But try the BGWorker first Commented Apr 22, 2015 at 9:39
  • 2
    Also check out msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx Commented Apr 22, 2015 at 9:42
  • Thanks, the docs were a big help. Commented Apr 22, 2015 at 11:47

1 Answer 1

6

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();
}));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.