我有一门课取决于TaskCompletionSource
该类的一个示例如下所示:
public ExampleClass
{
private TaskCompletionSource<string> _tcs;
public async Task<string> GetFooAsync()
{
_tcs = new TaskCompletionSource<string>();
return await _tcs.Task;
}
public void SetFoo(string value)
{
_tcs.SetResult(value);
}
}
我使用xUnit.net作为我的测试框架。
[Fact]
public async Task ReturnsString()
{
// Arrange
const string value = "test";
var myclass = new ExampleClass();
// Act -- Does not work. I don't know how to fix this.
var result = await myclass.GetFooAsync(); // Won't return before SetFoo is called
myclass.SetFoo(value); // Needs to be run after GetFooAsync is called
// Assert
Assert.Equal(value, result);
}
(见代码中的注释)