让WPF UI响应当执行按一下按钮

问题描述:

在我的WPF(C#)的应用中,当一个按钮被用户按下,执行一个漫长的过程。当按下按钮,直到完整的代码执行的窗口冻结,用户不能执行在窗口中的任何其他任务。我怎样才能使按钮单击代码作为后台进程,使窗口成为响应用户。我曾尝试以下方法,但没有成功。

In my wpf (c#) application , a long process is performed when a button is pressed by the user. When button is pressed until the complete code executed the window freezes and user cannot perform any other task in the window. How can I make the button click code as a background process, so that the window become responsive to the user. I have tried the following method, but was unsuccessful.

private void btn_convert_Click(object sender, RoutedEventArgs e)
{
    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, 
    new Action(() => { 

         WorkerMethod();
    }));
}



在哪里WorkerMethod与整个代码的功能。任何suggessions。

Where WorkerMethod is the function with the entire code. Any suggessions.

问候,结果
Sangeetha

Regards,
Sangeetha

您实际上已经在这里做了什么要求UI线程来运行通过调度的重任。

What you have actually done here is asking the UI thread to run your heavy task through the Dispatcher.

您应该创建一个新的线程/任务,并让它运行你的背景方法:

You should create a new thread/Task and let it run your background Method:

Thread t = new Thread(() => WorkerMethod());
t.Start();

有关进一步信息,请阅读本:

for further information read this:

WPF BackgroundWorker的调度与

理解调度员在WPF