如果代码执行时间超过 3 秒,我需要中止线程。我正在使用以下方法。
public static void Main(string[] args) {
if (RunWithTimeout(LongRunningOperation, TimeSpan.FromMilliseconds(3000))) {
Console.WriteLine("Worker thread finished.");
} else {
Console.WriteLine("Worker thread was aborted.");
}
}
public static bool RunWithTimeout(ThreadStart threadStart, TimeSpan timeout) {
Thread workerThread = new Thread(threadStart);
workerThread.Start();
bool finished = workerThread.Join(timeout);
if (!finished)
workerThread.Abort();
return finished;
}
public static void LongRunningOperation() {
Thread.Sleep(5000);
}
你能告诉我如何对有参数的函数做同样的事情吗?例如:
public static Double LongRunningOperation(int a,int b) {
}