gpt4 book ai didi

c# - 让单元测试返回 async void 不好吗?

转载 作者:行者123 更新时间:2023-11-30 15:57:33 25 4
gpt4 key购买 nike

我知道让方法返回 async void 是不好的做法,因为它很难测试,但是有什么理由让单元测试需要返回 async Task 而不是 async void?

基本上这样就可以了:

[Test()]
public async void MyTest()
{
//Some code to run test
//Assert Something
}

或者我应该这样做:

[Test()]
public async Task MyTest()
{
//Some code to run test
//Assert Something
}

最佳答案

引用Async/Await - Best Practices in Asynchronous Programming作者:斯蒂芬·克利里

Void-returning async methods have a specific purpose: to make asynchronous event handlers possible. It is possible to have an event handler that returns some actual type, but that doesn't work well with the language; invoking an event handler that returns a type is very awkward, and the notion of an event handler actually returning something doesn't make much sense. Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler. However, some semantics of an async void method are subtly different than the semantics of an async Task or async Task method.

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started.

最后几句话总结得很好。

长话短说,异步测试方法使用async Task

[Test()]
public async Task MyTest()
{
//Some code to run test
//Assert Something
}

您真的应该花一些时间阅读链接的文章。它的作者在该主题方面拥有更多资源,它将帮助您理解 async/await 背后的语义

关于c# - 让单元测试返回 async void 不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44834675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com