C# - End thread after timeout

By , 9/24/2012
(0 ratings)
This example shows how a method or a thread that executes a method ends after a certain timeout if the method is not yet finished.

Author: Günther Foidl, translation by Michael List
Translate to VB
#define LONG
using System;
using System.Threading;

namespace ConsoleApplication1
	class Program
		static void Main(string[] args)
			// Is required for thread-notification:
			AutoResetEvent signal = new AutoResetEvent(false);

			// Is required because a ThreadPool is being used
			Thread workerThread = null;

			// Through this variant, there is the advantage that
			// the worker-method does not have to be modified
			ThreadPool.QueueUserWorkItem((o) =>
				// Normally you are not able to access ThreadPool-threads -
				// using this trick you are.
				workerThread = Thread.CurrentThread;

				// Start Worker:

				// Notify, that Worker has finished:

			// Start timer -> waits 5 seconds and sets the signal.
			new Timer((o) => { signal.Set(); }, null, 5000, Timeout.Infinite);

			// Wait until the signal is set:

			// Check if the WorkerThread is still working. If yes, abort the
			// thread. If the worker would execute a loop, it could be
			// completed more elegant, by packing the Worker into a
			// class that implements RequestStop that sets a 
			// volatile-bool-field that would be queried every loop pass.
			// If this bool-field is set, end the work.
			if (workerThread != null && workerThread.IsAlive)

		/// <summary>
		/// Worker method
		/// </summary>
		static void Worker()
			Console.WriteLine("In Worker");

			// Simulate hard (long) work:
#if LONG
			Console.WriteLine("Worker finished.");



Log in, to comment!