.NET在X秒后抛出异常/引发事件

时间:2012-10-12 09:10:17

标签: c# .net

在长时间运行的C#方法中,我希望在经过几秒钟后抛出异常或引发事件。

这可能吗?

4 个答案:

答案 0 :(得分:2)

你可以使用一个计时器 - 将它设置为你想要的超时,然后在方法开始时启动它。

在方法的最后,禁用计时器 - 它只会在超时时触发,并且您可以连接到刻度事件。

var timer = new Timer(timeout);
timer.Elapsed = ElapsedEventHanler; // Name of the event handler
timer.Start();

// do long running process

timer.Stop();

我建议您阅读different timer classes - 这会让您知道哪一种最适合您的特定需求。

答案 1 :(得分:0)

使用System.Threading.Timer:

System.Threading.Timer t;
int seconds = 0;

public void start() {

    TimerCallback tcb = new TimerCallback(tick);
    t = new System.Threading.Timer(tcb);
    t.Change(0, 1000);          
}

public void tick(object o)
{
    seconds++;
    if (seconds == 60)
    {
        // do something
    }
}

答案 2 :(得分:0)

如果您打算停止长时间运行的方法,那么我认为为该方法添加取消支持将是一种更好的方法,而不是引发异常。

答案 3 :(得分:0)

尝试以下操作,它具有取消异常的功能(如果进程已完成)并在源线程上引发异常:

var targetThreadDispatcher = Dispatcher.CurrentDispatcher;
var tokenSource = new CancellationTokenSource();
var cancellationToken = tokenSource.Token;
Task.Factory.StartNew(() => 
{
    var ct = cancellationToken;

    // How long the process has to run
    Task.Delay(TimeSpan.FromSeconds(5));

    // Exit the thread if the process completed
    ct.ThrowIfCancellationRequest();

    // Throw exception to target thread
    targetThreadDispatcher.Invoke(() => 
    {
        throw new MyExceptionClass();
    }
}, cancellationToken);

RunProcess();

// Cancel the exception raising if the process was completed.
tokenSource.Cancel();
相关问题