Form freezes during while loop

前端 未结 3 1970
旧巷少年郎
旧巷少年郎 2021-02-10 12:27

I have a piece of code that checks if a certain application is running

while (Process.GetProcessesByName(\"notepad\").Length == 0)
{
     System.Threading.Thread         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-10 13:09

    You could always just start an asynchronous task to keep updating the UI

    Task f = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    //This would make the form become responsive every 500 ms
                    Thread.Sleep(500); //Makes the async thread sleep for 500 ms
                    Application.DoEvents(); //Updates the Form's UI
                }
            });
    

    Or this to run it on a different thread

    Task f = Task.Factory.StartNew(() =>
    {
    while (Process.GetProcessesByName("notepad").Length == 0)
        {
            System.Threading.Thread.Sleep(1000); //Does the while loop every 1000 ms
        }
    });
    

提交回复
热议问题