I have a method in which I have no control (let's assume it comes from another library):
private static void DoWork()
{
// I have no control over this method
while (true)
{
Console.WriteLine("Still working");
}
}
And I want to wait it some time (for example 20 seconds) and if the job isn't finished in this time to stop the code.
What I've tried so far:
Using Task-cancellation pattern isn't an option for me because I have no control over the method I am executing
Using only the
Task
class isn't an option because I cannot stop the execution of the task without using cancellation tokenvar taskToWaitAndKill = Task.Factory.StartNew(DoWork); taskToWaitAndKill.Wait(20000); // 20 seconds // The task cannot be stopped (aborted) and still runs...
Using the
Thread
class, waiting it and aborting it it is not an option because I need to wait all of the 20 seconds before stopping the code.var thread = new Thread(DoWork); thread.Start(); Thread.Sleep(20000); thread.Abort();
So my question is there a way in C# to wait fixed number of milliseconds for a code to execute and if the code finishes earlier not to wait any longer?