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."
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With