Search code examples
c#wpfmultithreadingbackground-process

Make wpf UI responsive when button click is performed


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();
    }));
}

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

Regards,
Sangeetha


Solution

  • 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 vs. Dispatcher

    Understanding “Dispatcher” in WPF