2

如何转换这样的代码:

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 或其他线程上或在我背后神奇地执行,就在我想要它们时,即由我自己决定 Task 何时“完成”并调用await 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(.. or Thread.Sleep(... or Task.Delay(...

4

1 回答 1

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");
}
于 2013-03-22T17:03:54.670 回答