老异步委托"具有异步VS&QUOT射后不理; [英] Fire-and-forget with async vs "old async delegate"
问题描述
我试图用一种新的语法来代替我的老发射后不管来电,希望能为更多的简单和它似乎是躲避我。这里有一个例子
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(),我怎么能称之为异步使用异步
/ 等待
在发射后不管的方式没有得到一个解决方案,比老办法
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"
推荐答案
避免异步无效
。它总共有错误处理棘手的语义;我知道有些人把它称为射后不理,但我通常使用短语火和崩溃。
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(),我怎么能称之为异步使用异步/等待在发射后不管的方式没有得到一个解决方案,比老办法更为复杂。
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"
您不需要异步
/ 等待
。只需调用它是这样的:
You don't need async
/ await
. Just call it like this:
Task.Run(A);
这篇关于老异步委托&QUOT;具有异步VS&QUOT射后不理;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!