使用 TPL 创建阻塞方法调用的超时
我有一个阻塞的库调用,一个 imap Idle 将在长时间运行的服务中等待电子邮件,我很偏执,不相信库永远不会错过电子邮件。可以通过并发调用 StopIdle 来取消 Idle 调用。如果它认为它仍然空闲,我每分钟调用 StopIdle 实现以下方法。
有更好的方法来执行以下操作吗?这种方法有效,但似乎我最终会占用一堆正在睡觉的线程池线程。
while (true)
{
// read unseen emails here ...
var cancelSource = new CancellationTokenSource();
var cancelToken = cancelSource.Token;
Task stopIdleOccasionally = Task.Factory.StartNew(() =>
{
Thread.Sleep(TimeSpan.FromMinutes(1));
if (cancelToken.IsCancellationRequested)
{
return;
}
client.StopIdle(); // This causes the Idle() call to return
},
cancelSource.Token);
client.Idle(); // This is the blocking call that I want to create a timeout for
cancelSource.Cancel();
}
I have a blocking library call, an imap Idle that will be in a long running service waiting for email, I'm paranoid and don't trust the library to never miss an email. The Idle call can be cancelled by a concurrent call to StopIdle. I implemented the following way to every minute call StopIdle if it thinks its still idling.
Is there a better way to do the following? This methods works but it seems like I will end up taking up a bunch of thread pool threads just sleeping.
while (true)
{
// read unseen emails here ...
var cancelSource = new CancellationTokenSource();
var cancelToken = cancelSource.Token;
Task stopIdleOccasionally = Task.Factory.StartNew(() =>
{
Thread.Sleep(TimeSpan.FromMinutes(1));
if (cancelToken.IsCancellationRequested)
{
return;
}
client.StopIdle(); // This causes the Idle() call to return
},
cancelSource.Token);
client.Idle(); // This is the blocking call that I want to create a timeout for
cancelSource.Cancel();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 Henk 的建议,我使用计时器将其重写为:
由于它是一个我无权访问代码的库,因此我无法更改 Idle 方法的行为
Using Henk's suggestion I rewrote it using a timer to be:
Since its a library that I don't have access to the code I can't alter the behavior of the Idle method