[英]How to properly cancel Task.Run with deadlock inside
I have a event that results in a deadlock when called and need a test to check for deadlock inside. 我有一个事件,当调用该事件会导致死锁,并且需要测试以检查内部的死锁。 But i don`t have a way to influance the client code.
但是我没有办法影响客户代码。
I allredy tryed several hacks like 我Allredy尝试过一些类似的技巧
Task t = Task.Run((Action)(() => { while(true); }), cts.Token);
And ways to insert a token inside a delegate but since deadlock is called within delegate - any await never happens. 以及在委托中插入令牌的方法,但是由于在委托中调用了死锁-永远不会发生等待。
void Action()
{
var request = WebRequest.Create(url);(requestUrl);
request.GetResponse();
received = instance.RequestReceived;
}
instance.ClientRequeest += (object sender, EventArgs e) => instance.Stop();
I have a EventHandler ClientRequest i can subscribe to. 我有一个可以订阅的EventHandler ClientRequest。 And an instance of a client that drops to deadlock when i try to stop it while it has some data to reply.
还有一个客户端实例,当我尝试停止它而有一些数据需要回复时,该实例陷入死锁。
ClientRequest has a await inside - witch, when asked to Stop and has a request - falls to infinite deadlock state - it awaits when request will be sent, and listener is allredy closed by Stop. ClientRequest内部有一个等待-当被问到Stop并且有一个请求时-陷入无限死锁状态-等待发送请求时,Stop一直关闭侦听器。 Wich is a posseble scenario in our case.
在我们的案例中,Wich是一种可能的情况。 But i don`t seem to find a way how to call a that event without going to deadlock myself inside the test.
但是我似乎没有找到一种方法来调用该事件而又不会在测试中陷入僵局。
So would be pretty thankfull for a proper way to make that Instance.ClientRequest wait for several seconds and throw exception or get cancelled or whatever - to avoid test hanging when deadlock actually happens. 因此,对于使Instance.ClientRequest等待几秒钟并抛出异常或被取消等问题的正确方法非常感激-避免在实际发生死锁时挂起测试。
If you have a Task
, and you know it will either complete in a fixed amount of time, or deadlock, you could:- 如果您有一个
Task
,并且知道它将在固定的时间内完成或陷入僵局,则可以:
var t = Task.Run(() =>
{
// do something that might deadlock, but if it doesn't will finish for sure in < 1000ms
});
if (!t.Wait(1000))
{
// He's dead Jim
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.