问题
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?
回答1:
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.
回答2:
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.
回答3:
One way is to use the TPL (Task Parallel library). Here is an article on Code Project about Using TPL in WPF.
来源:https://stackoverflow.com/questions/34253771/c-sharp-wpf-run-button-click-on-new-thread