异步与“旧异步委托"的即发即弃 [英] Fire-and-forget with async vs "old async delegate"

查看:35
本文介绍了异步与“旧异步委托"的即发即弃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用新语法替换旧的即发即弃调用,希望更简单,但我似乎无法理解.举个例子

I am trying to replace my old fire-and-forget calls with a new syntax, hoping for more simplicity and it seems to be eluding me. Here's an example

class Program
{
    static void DoIt(string entry) 
    { 
        Console.WriteLine("Message: " + entry);
    }

    static async void DoIt2(string entry)
    {
        await Task.Yield();
        Console.WriteLine("Message2: " + entry);
    }

    static void Main(string[] args)
    {
        // old way
        Action<string> async = DoIt;
        async.BeginInvoke("Test", ar => { async.EndInvoke(ar); ar.AsyncWaitHandle.Close(); }, null);
        Console.WriteLine("old-way main thread invoker finished");
        // new way
        DoIt2("Test2");   
        Console.WriteLine("new-way main thread invoker finished");
        Console.ReadLine();
    }
}

两种方法都做同样的事情,但是我似乎获得了什么(不需要 EndInvoke 并关闭句柄,恕我直言仍然有点值得商榷)我正在以新的方式失败等待 Task.Yield(),这实际上带来了一个新问题,即必须重写所有现有的异步 F&F 方法来添加单行代码.在性能/清理方面是否有一些无形的收益?

Both approaches do the same thing, however what I seem to have gained (no need to EndInvoke and close handle, which is imho still a bit debatable) I am losing in the new way by having to await a Task.Yield(), which actually poses a new problem of having to rewrite all existing async F&F methods just to add that one-liner. Are there some invisible gains in terms of performance/cleanup?

如果我不能修改后台方法,我将如何应用异步?在我看来没有直接的方法,我必须创建一个等待 Task.Run() 的包装器异步方法?

How would I go about applying async if I can't modify the background method? Seems to me that there is no direct way, I would have to create a wrapper async method that would await Task.Run()?

我现在发现我可能遗漏了一个真正的问题.问题是:给定一个同步方法 A(),我如何使用 async/await 以即发即弃的方式异步调用它,而不会得到一个解决方案比旧方式"更复杂

I now see I might be missing a real questions. The question is: Given a synchronous method A(), how can I call it asynchronously using async/await in a fire-and-forget manner without getting a solution that is more complicated than the "old way"

推荐答案

避免 async void.它在错误处理方面具有棘手的语义;我知道有些人称它为火灾和遗忘",但我通常使用火灾和崩溃"这个词.

Avoid async void. It has tricky semantics around error handling; I know some people call it "fire and forget" but I usually use the phrase "fire and crash".

问题是:给定一个同步方法 A(),我怎样才能以一劳永逸的方式使用 async/await 异步调用它,而不会得到比旧方法"更复杂的解决方案

The question is: Given a synchronous method A(), how can I call it asynchronously using async/await in a fire-and-forget manner without getting a solution that is more complicated than the "old way"

你不需要async/await.就这样称呼它:

You don't need async / await. Just call it like this:

Task.Run(A);

这篇关于异步与“旧异步委托"的即发即弃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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