使用 TPL 创建阻塞方法调用的超时

发布于 2024-11-19 02:40:04 字数 817 浏览 3 评论 0原文

我有一个阻塞的库调用,一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

从﹋此江山别 2024-11-26 02:40:04

根据 Henk 的建议,我使用计时器将其重写为:

Timer stopIdleTimeoutTimer = new Timer(
    _ => client.StopIdle(),
    null,
    TimeSpan.FromMinutes(1),
    TimeSpan.FromMilliseconds(-1));

client.Idle();

stopIdleTimeoutTimer.Dispose();

由于它是一个我无权访问代码的库,因此我无法更改 Idle 方法的行为

Using Henk's suggestion I rewrote it using a timer to be:

Timer stopIdleTimeoutTimer = new Timer(
    _ => client.StopIdle(),
    null,
    TimeSpan.FromMinutes(1),
    TimeSpan.FromMilliseconds(-1));

client.Idle();

stopIdleTimeoutTimer.Dispose();

Since its a library that I don't have access to the code I can't alter the behavior of the Idle method

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文