重写代码以利用C#异步功能

时间:2013-03-22 16:40:58

标签: c# async-await

如何转换此类代码:

public void Do2()
{
        Console.WriteLine("Do2::Before");
        Latent(() => Console.WriteLine("Do2::After"));
}
public void Latent(Action a)
{
     registeredActions.Add(a);
}
public void TriggerActions()
{
        foreach (Action a in registeredActions)
        {
            a();
        }
}

可以这样使用:

public async void Do1()
{
        Console.WriteLine("Do1::Before");
        await Latent();
        Console.WriteLine("Do1::After");
}

请注意,我不希望在ThreadPool或其他线程上执行任务,或者在我想要的时候神奇地在我背后执行任务,即在任务“完成”时自己决定并在等待Latent(),最有可能在调用Do1的同一个线程中。样品用法:

Console.WriteLine("Before Do");
ts.Do2();
Console.WriteLine("After Do, before triggering actions");
// ... do some other stuff and when it is the right time to "complete pending tasks"
ts.TriggerActions();
Console.WriteLine("After triggering actions");

我找不到任何解决方案,所有C#异步示例都谈论await client.GetStringAsync(..或Thread.Sleep(...或Task.Delay(...

1 个答案:

答案 0 :(得分:3)

您使用TaskCompletionSource<T>

Task Latent()
{
  var tcs = new TaskCompletionSource<object>();

  ... // Apply some logic here to eventually call "tcs.TrySetResult".

  return tcs.Task;
}

这可以这样使用:

public async Task Do1()
{
  Console.WriteLine("Do1::Before");
  await Latent();
  Console.WriteLine("Do1::After");
}