实现C#超时 [英] Implement c# timeout

查看:604
本文介绍了实现C#超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是不好的做法,用这种while循环? 也许这是更好地使用秒表,也许这个解决方案有一些缺陷?

Is it bad practice to use such while loop? Maybe it is better to use Stopwatch, or maybe this solution has some pitfalls?

    public void DoWork()
    {
        //do some preparation
        DateTime startTime = DateTime.Now;
        int rowsCount = 0;
        int finalCount = getFinalCount();
        do
        {
            Thread.Sleep(1000);
            rowsCount = getRowsCount(); // gets rows count from database, rows are added by external app.
        } while (rowsCount < finalCount && DateTime.Now - startTime < TimeSpan.FromMinutes(10));

    }

我看到这篇文章实现C#泛型超时, 但它太复杂简单的方案中使用 - 你需要考虑线程的同步,是正确的中止与否等等

I saw this article Implement C# Generic Timeout, but it is too complex to use in simple scenarios - you need to think about sync of threads, is it proper to abort them or not and so on.

推荐答案

据我了解,你想你的方法做了一些工作,直到把它完成,或直到一段时间已过?我会用一个秒表对于这一点,并检查经过的时间在一个循环:

As I understand it, you want your method to do some work until it's done or until some period of time has elapsed? I would use a Stopwatch for that, and check the elapsed time in a loop:

void DoWork()
{
    // we'll stop after 10 minutes
    TimeSpan maxDuration = TimeSpan.FromMinutes(10);
    Stopwatch sw = Stopwatch.StartNew();
    DoneWithWork = false;

    while (sw.Elapsed < maxDuration && !DoneWithWork)
    {
        // do some work
        // if all the work is completed, set DoneWithWork to True
    }

    // Either we finished the work or we ran out of time.
}

这篇关于实现C#超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆