जेनेरिक उदाहरण:
public static R WithTimeout<R>(Func<R> proc, int duration)
{
var wh = proc.BeginInvoke(null, null);
if (wh.AsyncWaitHandle.WaitOne(duration))
{
return proc.EndInvoke(wh);
}
throw new TimeOutException();
}
उपयोग:
var r = WithTimeout(() => regex.Match(foo), 1000);
अद्यतन:
रूप Christian.K से कहा, async धागा अभी भी चलते रहेंगे ।
यहाँ एक जहां धागा समाप्त कर देगा है:
public static R WithTimeout<R>(Func<R> proc, int duration)
{
var reset = new AutoResetEvent(false);
var r = default(R);
Exception ex = null;
var t = new Thread(() =>
{
try
{
r = proc();
}
catch (Exception e)
{
ex = e;
}
reset.Set();
});
t.Start();
// not sure if this is really needed in general
while (t.ThreadState != ThreadState.Running)
{
Thread.Sleep(0);
}
if (!reset.WaitOne(duration))
{
t.Abort();
throw new TimeoutException();
}
if (ex != null)
{
throw ex;
}
return r;
}
अद्यतन:
स्निपेट के ऊपर फिक्स्ड सही ढंग से अपवादों के साथ निपटने के लिए।
कार्य का उपयोग करके यह जवाब भी देखें: http://stackoverflow.com/a/13526507/492 ... मुझे नहीं पता कि यह सिल्वरलाइट में काम करता है या नहीं। –