c# wpf run button click on new thread

2019-09-06 05:32发布

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?

3条回答
贪生不怕死
2楼-- · 2019-09-06 05:49

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.

查看更多
我只想做你的唯一
3楼-- · 2019-09-06 05:52

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.

查看更多
来,给爷笑一个
4楼-- · 2019-09-06 06:02

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

查看更多
登录 后发表回答