我給它一點思想並用以下方法上來(基本上是一個什麼樣邁克爾,而我是編碼它寫了一個實現):
private static bool TimedMethodCaller(Delegate dlgt, int timeout,
params object[] args)
{
ManualResetEvent waitHandle = new ManualResetEvent(false);
Thread t = new Thread(new ThreadStart(delegate
{
dlgt.Method.Invoke(dlgt.Target, args);
waitHandle.Set();
}));
t.Start();
return waitHandle.WaitOne(timeout);
}
使用這種方法,你可以在任何發佈代表和您感覺的參數。它的缺點是不能處理返回值(但也可能以某種方式實現)。
你可以把它像這樣:
// parameter-less method call
bool success = TimedMethodCaller(new Action(ParamlessTestMethod), 100);
如果你想調用了參數的方法,你需要一個合適的委託:
// call with one parameter (using the Action<T> delegate of the framework
bool success = TimedMethodCaller(new Action<int>(TestMethod), 100, "text");
// call with several parameters using custom delegate that is defined like this:
// public delegate void SampleDelegate(string text, int numeric);
bool success = TimedMethodCaller(new SampleDelegate(TestMethod), 100, "text", 1);
不管你做什麼,請不要使用'Thread.Abort'或'Thread.Interrupt'。 :) – Joren 2009-09-23 21:27:04
會做。或者不......對。 ;) 謝謝大家的回覆。我想我們現在可能已經解決了這個問題,但我很高興在未來出現一些事情時提出這些建議。 – CodexArcanum 2009-09-30 16:07:19