在启动C#WPF中的另一个线程时,如何避免UI阻止?
我正在尝试执行线程而不阻止UI,我已经使用了此代码,但是当我执行应用程序时,它不会执行线程,单击dobutton
事件后,没有显示任何
public void DoThread()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += MyFunctionDoThread;
var frame = new DispatcherFrame();
worker.RunWorkerCompleted += (sender, args) => {
frame.Continue = false;
};
worker.RunWorkerAsync();
Dispatcher.PushFrame(frame);
}
private void Dobutton_Click(object sender, RoutedEventArgs e)
{
DoThread(); // Process will be executed
}
public void MyFunctionDoThread()
{
// Some Tasks
ProcessStartInfo startInfo = new ProcessStartInfo();
Process.Start(startInfo);
// ...
}
内容可以在不阻止UI的情况下执行任务(线程)吗?
I'm trying to execute a thread without blocking UI , I've used this code but when I execute my application , it won't execute the thread and nothing is shown after clicking on DoButton
event
public void DoThread()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += MyFunctionDoThread;
var frame = new DispatcherFrame();
worker.RunWorkerCompleted += (sender, args) => {
frame.Continue = false;
};
worker.RunWorkerAsync();
Dispatcher.PushFrame(frame);
}
private void Dobutton_Click(object sender, RoutedEventArgs e)
{
DoThread(); // Process will be executed
}
public void MyFunctionDoThread()
{
// Some Tasks
ProcessStartInfo startInfo = new ProcessStartInfo();
Process.Start(startInfo);
// ...
}
How I can perform a task ( thread ) without blocking the UI?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该真正使用任务/异步/等待任何背景工作。
背景工作者
相当古老。需要用
async
标记的方法,它不需要需要 返回任务的方法。返回任务是指南,以便呼叫者可以处理任何失败。但是,对于诸如按钮事件处理程序之类的事情,您处于生产线的末端,没有其他人可以处理任何故障,因此您应该确保尝试/捕获。You should really use Task/async/await for any background work.
BackgroundWorker
is rather old.await requires the method to be marked with
async
, it does not require the method to return a task. It is a guideline to return a task, so that the caller can deal with any failures. But for things like button event handlers you are at the end of the line, there is no one else to deal with any failure, so you should instead make sure you do it yourself with a try/catch.