繁体   English   中英

如何在不阻塞主线程的情况下暂停 C# 代码执行?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM