异步执行中的同步睡眠?

时间:2013-08-22 02:21:33

标签: c# asynchronous

有没有办法以某种方式创建一种方法来睡眠执行函数异步模仿thread.sleep?

例如我有

 Workthread run()
 {
 while (true)
 {
 //All calls cannot pause inside, async
 CallWorkFunction();
 CallOtherWorkFuctuion();
 Callthirdworkfunction();
 thread.sleep(0x10);
  curtick++;
 }
 }

//CallWorkFunction()

if (nexttick - curtick > 0)
   return;
foreach (var item in collection.ToList())
{
   if (!item.IsReady)
       continue;
   collection.Remove(item);
   ProcessItem(item);
   nexttick = curtick + 20;
   return;
}

如果nexttick可以像线程Thread.Sleep()一样工作而不停止执行,那么这个函数会更好。由于异步代码变成了一堆基于状态的检查,其中许多可以用正确的暂停替换。

1 个答案:

答案 0 :(得分:0)

尝试这样做:

async Workthread run()
{
    while (true)
    {
     //All calls cannot pause inside, async
     CallWorkFunction();
     CallOtherWorkFuctuion();
     Callthirdworkfunction();

     await Task.Delay(0x10);

     curtick++;
    }
}