[英]How to Pause C# code execution without blocking main thread?
好的,所以我們有一個程序,我們要在其中為 WinForm 上的控件設置動畫,然后恢復剩余代碼塊的后續操作。 這是示例代碼。
該函數在 WinForm 上,大概在主線程上運行
Private void DoThisWork();
{
do some work here
animateControls()
//<NEED TO PAUSE HERE WHILE THE GUI ANIMATES AND UPDATES DISPLAYING THE ANIMATION OF THE CONTROL>
//Tried Option 1: thread.sleep. When we do this the main thread blocks and the animation is //not seen. The control is directly painted at x1,y1 and thats it, the intermediate rendering is not seen
// Tried Option 2: Application.DoEvents. This works very well except that the CPU maxes out and the animation then appears very jittery
continue doing remaining work // must execute only after animateControls() completes the animation part.
}
現在, animateControls()
只是一個計時器上的函數,它將控件從 (x,y) 點移動到 (x1,y1) 點,這大約需要 3 秒。
SuspendLayout 和 ResumeLayout 不會強制 GUI 更新,因為 thread.sleep 導致主線程阻塞,所以一切實際上都處於停滯狀態。
使用不同的線程為 GUI 設置動畫似乎沒有幫助,因為我仍然需要完成整個動畫。
此外,我無法在動畫代碼中添加任何內容,因為它是從多個函數調用的,因此被用作公共函數。
你走錯了路。 把你的工作放在一個單獨的線程上,讓你的 UI 線程做你的動畫,直到工作線程完成。
BackgroundWorker 類可能會派上用場。 http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.