Visual Studio函数未按顺序完成操作

Fly*_*ynn 2 .net c# visual-studio-2010

我有一个似乎没有按预定顺序工作的功能.顺便说一下,这完全在Visual Studio的C#中.

这里我们有一个被点击的按钮(步骤4),应该发生的是按钮应该变成红色,文本"请等待......"直到进程加载,然后它将变为绿色与程序的名称.但是,它只是加载程序并使用默认文本保持默认灰色,直到进程加载,然后使用程序名称直接更改为绿色.由于某种原因,它正在跳过红色,请等待文本部分.这是代码:

    private void Step4_Click(object sender, EventArgs e)
    {
        Step4.BackColor = Color.DarkRed;
        Step4.Text = "Please Wait...";
        string strMobileStation = "C:\\MWM\\MobileStation\\Station.exe";
        Process MobileStation = Process.Start(strMobileStation);
        MobileStation.WaitForInputIdle();
        Step4.BackColor = Color.Lime;
        Step4.Text = "Mobile Station";
    }
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 6

问题是你在用户界面线程上这样做.

在UI线程上执行此操作时,将阻止UI线程,这反过来意味着用户界面无法处理消息.方法完成后,将处理消息,并显示最终结果.

处理此问题的正确方法是将"工作"(等待进程)移动到后台线程中.

你可以通过Task课程来做到这一点,即:

private void Step4_Click(object sender, EventArgs e)
{
    Step4.BackColor = Color.DarkRed;
    Step4.Text = "Please Wait...";

    Task.Factory.StartNew( () =>
    {
      string strMobileStation = "C:\\MWM\\MobileStation\\Station.exe";
      Process MobileStation = Process.Start(strMobileStation);
      MobileStation.WaitForInputIdle();
    })
    .ContinueWith(t =>
    {
      Step4.BackColor = Color.Lime;
      Step4.Text = "Mobile Station";
    }, TaskScheduler.FromCurrentSynchronizationContext());
}
Run Code Online (Sandbox Code Playgroud)