重写code,以利用C#异步功能 [英] Rewriting code to take advantage of C# async feature

查看:121
本文介绍了重写code,以利用C#异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何变换这类code:

How to transform such code:

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");
}

请注意,我不希望被在线程池或其他线程或奇迹般地在我背后执行任务,只是当我想他们,即由我自己决定何时任务是已完成,并呼吁任何code是之后的等待潜()的,最有可能在同一个线程中DO1被调用。示例用法:

Note that I do not want Tasks to be executed on ThreadPool or on other threads or magically behind my back, just when I want them to, i.e. decide by myself when Task is "completed" and call whatever code is after await Latent(), most likely in the same thread as Do1 is called. Sample usage:

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#异步采样谈论等待client.GetStringAsync(..和Thread.sleep(...或者Task.Delay(...

I couldn't find any solution for this, all C# async samples talk about await client.GetStringAsync(.. or Thread.Sleep(... or Task.Delay(...

推荐答案

您使用 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");
}

这篇关于重写code,以利用C#异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆