我需要监视一个任务,如果它花费的时间超过定义的超时时间,就将其终止。
到目前为止,我做了很多尝试,从创建线程和发出线程中止等开始。然后,我决定使用 TPL。
您必须假设 WorkItem 是一个黑匣子。您无权访问其源代码。因此,重写它以使其跟踪令牌是不现实的。这需要从外部控制。
有任何想法吗?
public class WorkItem : IDisposable
{
private System.Diagnostics.Stopwatch _watch = new System.Diagnostics.Stopwatch();
private List<string> _messages = new List<string>();
public void WriteMessage(string message)
{
_messages.Add(message);
}
public void Run()
{
for (int i = 1; i <= 25; i++)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Slept one second after {0} iteration.", i);
}
}
public void Dispose()
{
_watch.Stop();
Console.WriteLine("Disposed... lived for {0} milliseconds", _watch.ElapsedMilliseconds);
}
}
class Program
{
static void Main(string[] args)
{
int timeout = 5000;
WorkItem item = new WorkItem();
System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Factory.StartNew<WorkItem>((arg) =>
{
WorkItem currentWorkItem = arg as WorkItem;
currentWorkItem.Run();
return currentWorkItem;
}, item);
bool wait = task.Wait(timeout);
if (wait == false)
{
Console.WriteLine("It took more than {0} ms.", timeout);
// Need a way to kill the task.
}
Console.WriteLine("Okay Waiting");
Console.ReadKey();
}
}