1

In my WPF, .Net 4.5 application I have some long running tasks that occur after user interactions.

If for example a user clicks a button, whats the best way to run the button action on a separate thread so that the user can keep interacting with the application while the processing is being done?

lextechnica
  • 103
  • 2
  • 6
  • The button click will always run in the UI thread. Look for some multithreading tutorial, like [this one](https://msdn.microsoft.com/en-us/library/ck8bc5c6.aspx) from the MSDN. – Camilo Terevinto Dec 13 '15 at 17:10

3 Answers3

3

For Long running tasks you can use async/await. It's designed to replace the background worker construct, but it's completely down to personal preference.

here's an example:

private int DoThis()
{
      for (int i = 0; i != 10000000; ++i) { }
      return 42;
}

public async void ButtonClick(object sender, EventArgs e)
{
    await Task.Run(() => DoThis());
} 

Something like this would not lock up the UI whilst the task is completing.

Daniel Hakimi
  • 1,153
  • 9
  • 16
  • Genius. I ♥ OneLiners. *Could be a slogan for a t-shirt to counter this **I ♥ preferedCityHere** guys!* – C4d Jul 13 '16 at 22:19
  • Not working , after testing this , it will not execute the function. – abdou93 Jun 28 '22 at 10:04
1

Use the BackgroundWorker class. You will need to move your code to the worker and call the Run function of it from the button. Here is a nice answer on StackOverflow on how to use it.

Community
  • 1
  • 1
ave
  • 287
  • 13
  • 27
0

One way is to use the TPL (Task Parallel library). Here is an article on Code Project about Using TPL in WPF.

amuz
  • 334
  • 2
  • 11