What does messageBox.Show() do in order to stop the execution of a UI thread?

天大地大妈咪最大 提交于 2019-12-01 14:40:11

As I wrote in my comment, you should really use the (main) UI thread for UI only. Perform any other long-running non-UI operations on worker threads.

You might not mind the "hang" UI for 10 seconds, but users will surely be annoyed. Also, blocking the UI thread will cause Windows to think that your app is frozen, so you'll get that nice "not responding" badge and all related stuff. This not only looks awful but also can cause various side-effects.

You should really take a look around and see what .NET offers you for such kind of problems.

Look, this is your workflow:

  1. Print a message
  2. Start initialization
  3. ???
  4. Initialization is complete --> print "done"
  5. Start operation

What is this? This is an asynchronous processing. You start an action and continue asynchronously - that means, only when the action is completed.

.NET offers you a lot of tools for that, e.g. the APM (Asynchronous Programming Model). But the most neat and powerful way for implementing asynchronous processing is the TAP - Task-based Asynchronous Programming pattern, better known as async/await.

Look, your problem can be solved with a couple of lines using the TAP:

async void StartTest_btn_Click(object sender, RoutedEventArgs e)
{
    OutputText("Please Wait\r\n");      

    // Set_COMM_MODE will be executed on a worker thread!
    // The main (UI) thread won't block. It will continue.
    // But the StartTest_btn_Click method itself will pause until the task is finished.
    await Task.Run(() => Set_COMM_MODE("02"));

    // This line will only be executed, after the Set_COMM_MODE call is completed;
    // furthermore, it will be executed on the UI thread again!
    OutputText("Done\r\n");
}

You should really learn more about the modern programming techniques, which the TAP is one of.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!