0

我想运行一个函数 ( funcA) 并使用另一个函数 ( timerFunc) 作为计时器。如果正在运行的函数 ( funcA) 已经运行了 10 秒,我想使用计时器函数 ( timerFunc) 退出它。这可能吗?基本上我想做的是:

void funcA() {
    // check event 1
    // check event 2
    // check event 3
    // time reaches max here! --exit--
    //check event 4
}

如果不是,那么处理这种情况的最佳方法是什么?我考虑过使用秒表,但我不确定这是否是最好的做法,主要是因为我不知道在什么事件之后会达到超时。

4

3 回答 3

2
Thread t = new Thread(LongProcess);
t.Start();
if (t.Join(10 * 1000) == false)
{
    t.Abort();
}
//You are here in at most 10 seconds


void LongProcess()
{
    try
    {
        Console.WriteLine("Start");
        Thread.Sleep(60 * 1000);
        Console.WriteLine("End");
    }
    catch (ThreadAbortException)
    {
        Console.WriteLine("Aborted");
    }
}
于 2012-06-11T20:13:11.437 回答
1

您可以将所有事件放入 Action 数组或其他类型的委托中,然后遍历列表并在适当的时间退出。

或者,在后台线程或任务或其他线程机制中运行所有事件,并在到达适当时间时中止/退出线程。硬中止是一个糟糕的选择,因为它可能导致泄漏或死锁,但您可以在适当的时候检查 CancellationToken 或其他东西。

于 2012-06-11T19:46:18.473 回答
1

我会创建一个列表,然后非常快:

class Program
{
    static private bool stop = false;
    static void Main(string[] args)
    {
        Timer tim = new Timer(10000);
        tim.Elapsed += new ElapsedEventHandler(tim_Elapsed);
        tim.Start();

        int eventIndex = 0;
        foreach(Event ev in EventList)
        {
           //Check ev
            // see if the bool was set to true
            if (stop)
                break;
        }
    }

    static void tim_Elapsed(object sender, ElapsedEventArgs e)
    {
        stop = true;
    }
}

这应该适用于一个简单的场景。如果它更复杂,我们可能需要更多细节。

于 2012-06-11T20:04:19.603 回答