等待的作品,但呼吁task.Result挂起/死锁 [英] await works but calling task.Result hangs/deadlocks
问题描述
我有以下四个测试,当我运行它的最后一挂,我的问题是,为什么出现这种情况:
I have the following four tests and the last one hangs when I run it, my question is why this happens:
[Test]
public void CheckOnceResultTest()
{
Assert.IsTrue(CheckStatus().Result);
}
[Test]
public async void CheckOnceAwaitTest()
{
Assert.IsTrue(await CheckStatus());
}
[Test]
public async void CheckStatusTwiceAwaitTest()
{
Assert.IsTrue(await CheckStatus());
Assert.IsTrue(await CheckStatus());
}
[Test]
public async void CheckStatusTwiceResultTest()
{
Assert.IsTrue(CheckStatus().Result); // This hangs
Assert.IsTrue(await CheckStatus());
}
private async Task<bool> CheckStatus()
{
var restClient = new RestClient(@"https://api.test.nordnet.se/next/1");
Task<IRestResponse<DummyServiceStatus>> restResponse = restClient.ExecuteTaskAsync<DummyServiceStatus>(new RestRequest(Method.GET));
IRestResponse<DummyServiceStatus> response = await restResponse;
return response.Data.SystemRunning;
}
我使用这个扩展方法 restsharp RESTClient实现:
public static class RestClientExt
{
public static Task<IRestResponse<T>> ExecuteTaskAsync<T>(this RestClient client, IRestRequest request) where T : new()
{
var tcs = new TaskCompletionSource<IRestResponse<T>>();
RestRequestAsyncHandle asyncHandle = client.ExecuteAsync<T>(request, tcs.SetResult);
return tcs.Task;
}
}
public class DummyServiceStatus
{
public string Message { get; set; }
public bool ValidVersion { get; set; }
public bool SystemRunning { get; set; }
public bool SkipPhrase { get; set; }
public long Timestamp { get; set; }
}
为什么最后的测试挂?
Why does the last test hang?
推荐答案
您正在运行,到我描述的对在我的博客和 MSDN文章:在异步
法正试图安排其延续到了被阻止通过调用结果$一个线程C $ C>。
You're running into the standard deadlock situation that I describe on my blog and in an MSDN article: the async
method is attempting to schedule its continuation onto a thread that is being blocked by the call to Result
.
在这种情况下,你的的SynchronizationContext
是用于NUnit的执行异步无效
测试方法之一。我会尝试使用异步任务
的测试方法来代替。
In this case, your SynchronizationContext
is the one used by NUnit to execute async void
test methods. I would try using async Task
test methods instead.
这篇关于等待的作品,但呼吁task.Result挂起/死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!