1

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 token

    var 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?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123

1 Answers1

2

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.

Do it differently and you can do it:

var timeout = TimeSpan.FromSeconds(20);
var started = DateTime.UtcNow;
var thread = new Thread(DoWork);
thread.Start();
while (thread.IsAlive && DateTime.UtcNow - started < timeout)
{
    Thread.Sleep(10);
    // Do whatever here
}

// timeout occured, aborting
if (thread.IsAlive)
    thread.Abort();

However, killing a Thread by Abort is a dangerous operation, might cause surprises. If you really has to execute foreign codes, which you cannot control (eg. 3rd party plugins), then you should create an AppDomain for them. In case of any errors (including ThreadAbortException) you could unload the AppDomain securely.

György Kőszeg
  • 17,093
  • 6
  • 37
  • 65