简体   繁体   中英

Start and wait for new thread without blocking UI thread

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM