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?

ThomasArdal
  • 4,999
  • 4
  • 33
  • 73
abdou31
  • 45
  • 1
  • 8

1 Answers1

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.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • Sorry, but I'm getting an error that said cannot assign void to implicitly-typed variable – abdou31 Jun 21 '22 at 14:33
  • @abdou31 I'm guessing your method returns void, then skip the `var result =` part – JonasH Jun 21 '22 at 18:48
  • Yes I fixed this but the progressbar for now won't start , I didn't know why?? – abdou31 Jun 27 '22 at 11:26
  • @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. – JonasH Jun 27 '22 at 12:19