本范例演示了C#开发GUI程序时如何避免一个超长处理过程占用全部资源,导致界面不能响应用户事件的方法
// You need the Threading library to use the // "Thread.Sleep" function // using System.Threading; // This boolean value can be used to stop the // process below bool UserHitCancel = false; this.progressBar.Maximum = 100; // Loop 100 times for (int i = 0; (i < 100 && !UserHitCancel); i++) { // Update a progressbar or any other control this.progressBar.Value = i; // This function checks if the user fired any // events, like clicks on a cancel button and // allowes the application to react Application.DoEvents(); // This tells the current thread to sleep for 50 milliseconds, // so that the user can see the progress bar filling up Thread.Sleep(TimeSpan.FromMilliseconds(50)); }