我读到void从C#async调用返回并不好.但我有以下情况:
public async void MainFunction()
{
await DoSomething()
await DoSomethingMore()
}
public void DoSomething()
{
//some code that I want to execute (fire and forget)
}
public void DoSomethingMore()
{
//some code that I want to execute (fire and forget)
}
Run Code Online (Sandbox Code Playgroud)
因为我只想要执行该函数而根本没有返回.我应该这样保留它,还是应该Task从DoSomething()返回?如果我将其更改为返回Task,因为我的代码根本不需要返回任何内容,我应该返回什么?
我有这个代码
public class ClassToTest
{
private readonly IRepository repository;
public ClassToTest(DI GOES HERE){...}
public DoSomething()
{
Task.Run(async () => {
//some code
repository.ExecuteAsync();
}
}
}
public class Repository : IRepository
{
public Task ExecuteAsync()
{
using (var connection = new SqlConnection(DbConfiguration.DatabaseConnection))
{
return connection.ExecuteAsync(storedProcedure, parameters, commandType: CommandType.StoredProcedure, commandTimeout: Configuration.TransactionTimeout);
}
}
}
[Test]
public void TestMethod()
{
var repository = new Mock<IRepository>;
var classToTest = new ClassToTest();
classToTest.DoSomething();
repository.Veryfy(p => p.ExecuteAsync(), Times.Once());
}
Run Code Online (Sandbox Code Playgroud)
测试失败并显示此消息
模拟一次的预期调用,但是是0次:p => p.ExecuteAsync()
有谁知道为什么?
谢谢