Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackgroundWorker alternatives for Windows Forms

Tags:

c#

.net

winforms

Is it possible to do something like this in a Windows Forms app?

I'm trying to find other ways of updating the UI instead of using the BackgroundWorker all the time. Maybe something like this?:

public List<String> results = new List<String>();

private void button1_Click(object sender, EventArgs e)
{
    When(SomeLongRunningMethod("get") == true)
    {
        // LongRunningMethod has completed.
        // display results on Form.
        foreach(string result in results)
        {
            this.Controls.Add(new Label() { Text = result; Location = new Point(5, (5 * DateTime.Now.Millisecond)); });
        }
    }
}

public void SomeLongRunningMethod(string value)
{
    if(value == "get")
    {
        // Do work.
        results.Add("blah");
    }
}

The above basically says, "Do this and when you're done, add the results to the form."

like image 626
jay_t55 Avatar asked Feb 12 '23 09:02

jay_t55


2 Answers

I recommend you use async/await with Task.Run. Note that returning the results is cleaner:

private void button1_Click(object sender, EventArgs e)
{
  var results = await Task.Run(() => SomeLongRunningMethod("get"));
  foreach(string result in results)
  {
    this.Controls.Add(new Label() { Text = result; Location = new Point(5, (5 * DateTime.Now.Millisecond)); });
  }
}

public List<string> SomeLongRunningMethod(string value)
{
  var results = new List<string>();
  if(value == "get")
  {
    // Do work.
    results.Add("blah");
  }
  return results;
}

I have a series of blog posts on my blog that describe how Task.Run acts as a replacement for BackgroundWorker.

like image 75
Stephen Cleary Avatar answered Feb 15 '23 10:02

Stephen Cleary


What you are looking for is async / await:

private async void button1_Click(object sender, EventArgs e)
{
    string result = await SomeLongRunningMethod("www.stackoverflow.com");

    // LongRunningMethod has completed.
    ....
}

public Task<string> SomeLongRunningMethod(string uri)
{
    // Example
    return WebClient.DownloadStringAsync(new Uri(uri));
}

An example for a compute intensive operation would be this:

public Task<string> SomeLongRunningMethod()
{
  return Task.Factory.StartNew(() => 
  {
     // Perform work which requires some time to complete ...
     return "your result";
  });   
}

There is lots of information on this topic in the web. Here is a link for an extensive introduction on the topic:

http://msdn.microsoft.com/en-us/library/hh191443.aspx

like image 41
David Roth Avatar answered Feb 15 '23 11:02

David Roth