abdou31
abdou31

Reputation: 75

How to avoid UI blocking when starting another thread in C# WPF?

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?

Upvotes: 0

Views: 1146

Answers (1)

JonasH
JonasH

Reputation: 36341

You should really use Task/async/await for any background work. BackgroundWorker is rather old.

public async void Dobutton_Click(object sender, RoutedEventArgs e)
{
    try{
        var result = await Task.Run(MyFunctionDoThread);
        // Update the UI, or otherwise deal with the result
    }
    catch{
        // deal with failures, like showing a dialog to the user
    }
}

how can I use it , the await require to return task action

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.

Upvotes: 1

Related Questions