小编mll*_*ll5的帖子

使用ContinueWith自我继续任务

我有一个需要定期运行的任务.我的第一个实现是:

public static void CheckTask(CancellationTokenSource tokenSource)
{
   do
   {
      // Do some processing
      Console.WriteLine("Processing");

      // Sleep awhile and wait for cancellation
      // If not cancelled, repeat
   } while (!tokenSource.Token.WaitHandle.WaitOne(1500));

   Console.WriteLine("Bye bye");
}
Run Code Online (Sandbox Code Playgroud)

此任务是这样开始的:

CancellationTokenSource tokenSource = new CancellationTokenSource();
Task task = null;
task = new Task((x)=> {
    CheckTask(tokenSource);
    //CheckTask2(t, (object)tokenSource);
}, tokenSource.Token);
task.Start();
Run Code Online (Sandbox Code Playgroud)

然后我想而不是在任务中循环,为什么不使用ContinueWith重新安排它呢?我的下一个实现是这样的:

public static void CheckTask2(Task task, object objParam)
{
   CancellationTokenSource tokenSource = (CancellationTokenSource)objParam;
   // Do some processing
   Console.WriteLine("Processing");
   // Sleep awhile and wait for cancellation
   if(tokenSource.Token.WaitHandle.WaitOne(1500))
   { …
Run Code Online (Sandbox Code Playgroud)

.net c# task-parallel-library async-await

1
推荐指数
1
解决办法
654
查看次数

标签 统计

.net ×1

async-await ×1

c# ×1

task-parallel-library ×1