c# wpf run button click on new thread

这一生的挚爱 提交于 2020-01-25 12:44:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!