0

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?

3
  • have you check this one: stackoverflow.com/questions/45123128/… Commented Jun 17, 2022 at 14:20
  • 1
    Why not use async await? Commented Jun 17, 2022 at 14:40
  • @Charlieface , how can I use it , the await require to return task action? Commented Jun 17, 2022 at 15:13

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, but I'm getting an error that said cannot assign void to implicitly-typed variable
@abdou31 I'm guessing your method returns void, then skip the var result = part
Yes I fixed this but the progressbar for now won't start , I didn't know why??
@abdou31 If you have a progress bar you need to ensure it is only updated from the UI thread. But that seem like it should be a separate question, or just lookup examples on how to correctly use a progress-bar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.