2012-10-12 13 views
1

在長時間運行的C#方法中,我想拋出異常,或者在經過若干秒後引發事件。.NET在X秒後拋出異常/引發事件

這可能嗎?

+2

使用[System.Timer](http://msdn.microsoft .com/en-us/library/system.timers.timer.aspx) – Habib

+0

您是否嘗試過使用'Timer'?我只能認爲在您的方法運行的線程上不會引發異常。 – LukeHennerley

+1

@Habib你認爲這個異常會發生在另一個線程上,因此該方法很可能會繼續嗎?不是那麼簡單,我不認爲? – LukeHennerley

回答

2

您可以通過使用計時器來完成此操作 - 將其設置爲您希望的超時時間,並在方法開始時啓動它。

在該方法的最後,禁用計時器 - 它只會在超時時觸發,並且可以掛鉤到tick事件。

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

// do long running process 

timer.Stop(); 

我建議您閱讀了上different timer classes - 這會讓你知道哪個是最適合您的特定需求。

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 
    } 
} 
0

如果您打算停止長時間運行的方法,那麼我想添加取消支持的方法將是一個更好的辦法而不是引發異常。

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();