用例的异步void的方法,重新审视 [英] Use cases for async void methods, revisited

查看:216
本文介绍了用例的异步void的方法,重新审视的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,最好的做法是避免 异步无效方法什么,但异步事件处理程序,并有相当强大的专家意见与其他使用案例。我不过只是参与了一个简短的讨论关于有用异步无效方法和我有几个问题:

  • 如何框架跟踪未决异步无效方法,包括事件处理程序?有没有可能是一个方式来获得他们的最新列表,或取消这些( EDITED :跟踪就很有可能通过安装一个自定义的的SynchronizationContext )<? / LI>
  • 他们是任何可用于发射后忘记登录scenarious?我觉得他们其实可能是,只要在正确的时间戳记是preserved在方法的开始,同时,它还是同步执行。
解决方案
  

如何框架保持挂起的异步void的方法,包括事件处理程序的轨道上吗?

该框架没有做什么特别的跟踪异步无效的方法。他们就像任何其他异步方法。

另外,你的方法要么有一个适当的签名或没有;事件处理程序不关心,也没有逻辑来检测或异步工作的具体。

自定义调度程序将能够保持运行的任务轨道,但没有任何具体的知识,如果一个是从一个异步方法无效或不。我不认为这是正确的解决方案呢 - 如果你发现自己需要保持一个异步方法无效的轨道,你需要重新考虑你的设计

  

他们是任何可用于发射后忘了记录的场景?我想,他们实际上可能是,只要在正确的时间标记为preserved

我不知道你所说的时间戳是什么意思?

异步无效是好的任何方法,其中主叫要么永远需要关心的方法调用,或者它正在结果的通知别处的结果​​。这些情况应该是非常非常罕见。

消防和忘记可能是这样一个场景,虽然我觉得人们经常误用火和忘记,并最终从自己只是隐藏重要的错误。

I'm aware that the best practice is to avoid async void methods for anything but async event handlers, and there is quite strong expert opinion against other use cases. I was however just involved in a brief discussion about usefulness of async void methods and I've got a couple of questions:

  • How does the Framework keep track of pending async void methods, including event handlers? Is there possibly a way to obtain the current list of them or cancel them (EDITED: tracking is probably possible by installing a custom SynchronizationContext)?
  • Are they any useful for fire-and-forget logging scenarious? I think they actually may be, as long as the correct time-stamp is preserved at the beginning of the method, while it still executes synchronously.

解决方案

How does the Framework keep track of pending async void methods, including event handlers?

The framework doesn't do anything special to keep track of async void methods. They're just like any other async method.

Also, your method either has a proper signature or it doesn't; event handlers do not care and have no logic to detect or work with async specifically.

A custom scheduler would be able to keep track of running tasks, but not have any specific knowledge if one is from an async void method or not. I don't think this is the right solution anyway -- if you find yourself needing to keep track of an async void method, you need to rethink your design.

Are they any useful for fire-and-forget logging scenarios? I think they actually may be, as long as the correct time-stamp is preserved

I don't know what you mean by a timestamp?

Async void is fine for any method where the caller will either never need to care about the result of the method call, or where it is being notified of the result elsewhere. These cases should be very exceedingly rare.

Fire-and-forget might be one such scenario, though I feel people often misuse fire-and-forget and end up just hiding important bugs from themselves.

这篇关于用例的异步void的方法,重新审视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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