Skip to main content

Simple example of aborting a thread after a specified amount of time has elapsed.

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        int timeOutSeconds = 2; // timeout work after 2-seconds.

        Thread thread = new Thread( () => {
            Console.WriteLine("Doing Threaded Work...");
            Thread.Sleep(TimeSpan.FromSeconds(3)); // make work take 3 seconds...
        });
        thread.Start();

        if (!thread.Join(TimeSpan.FromSeconds(timeOutSeconds)))
        {
            thread.Abort();
            Console.WriteLine("Timeout Exceeded (after {0}-seconds)... Doing Threaded Work.",
                timeOutSeconds);
        }
    }
}