【发布时间】:2012-07-12 23:38:15
【问题描述】:
如果代码执行时间超过 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) {
}
【问题讨论】:
-
这可能会给你一个线索?线程构造函数(ParameterizedThreadStart)msdn.microsoft.com/en-us/library/1h2f2459.aspx
-
附注:Thread.Abort() 被认为是不安全的,它可能会破坏或死锁您的应用程序。取决于 LongRunningOperation() 正在执行的内容。
标签: c# multithreading parameter-passing abort