Implement Timeout in C#
by calendarw on Oct.24, 2007, under coding snippet
最近要幫個 hardware 寫返個 timeout, 主要既目的唔想佢 hold 咁耐, 好似 hang 左咁, 所以就係網上搵左呢個較好既方法.
其實主要係用左 Delegate, define 個 delegate 同target function 同樣 return type 同 parameter, 之後將果個 function 放係 delegate 個 constructor 果度, private 左之前果個 function, 將外部既 code call 新既 method (Execute), Set 埋個 Timeout 可以自己做個 TimeoutException~~
delegate int WorkDelegate(string arg);
public int Execute(string arg)
{
WorkDelegate d = new WorkDelegate(TargetFunction);
IAsyncResult res = d.BeginInvoke(arg, null, null);
if (res.IsCompleted == false)
{
//Timeout when execute more than 10 sec
res.AsyncWaitHandle.WaitOne(10000, false);
if (res.IsCompleted == false)
{
throw new TimeoutException("Timeout");
}
}
return d.EndInvoke((AsyncResult)res);
}

