Start and wait for new thread without blocking UI thread

Viewed 335

I have a method that can’t run asynchronously. In order not to block the UI thread, I want to open a new thread and run the method in it. However, this thread must be waited for the additional code to be executed according to the method to work. The method that cannot run asynchronously converts a file and it takes some time depending on how big the file is. But I want the window to remain usable, so that the UI thread is not blocked. I have already searched on the Internet, but found nothing suitable.

1 Answers
async void button1_Click(....)
{
   label1.Text = "busy...";
   await Task.Run(() => { RunOldCode(); });
   label1.Text = "done.";   // safe to use the UI
}

Note that async void should only be used for (simple) eventhandlers. It is problematic in most other situations.

Related