dotnet-Snippets.com
Add Snippet
Snippets: 136 | Registered User: 138
Main Menu

Home
Random Snippet
Contact Us
Imprint
RSS Feeds

All languages
C#
VB.NET
C++
ASP.NET
Google Ads
End thread after timeout

Author: Michael List
Programming Language: C# Rating:
not yet rated

Views: 1715

Description:

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




C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#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:
				Worker();

				// Notify, that Worker has finished:
				signal.Set();
			});

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

			// Wait until the signal is set:
			signal.WaitOne();

			// 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)
				workerThread.Abort(); 

			Console.WriteLine("Finished.");
			Console.ReadKey();
		}
		//---------------------------------------------------------------------
		/// <summary>
		/// Worker method
		/// </summary>
		static void Worker()
		{
			Console.WriteLine("In Worker");

			// Simulate hard (long) work:
#if LONG
			Thread.Sleep(200000);
#else
			Thread.Sleep(1000);
#endif
			Console.WriteLine("Worker finished.");
		}
	}
}

This Snippets could be interesting for you:

Poor Excellent
1 2 3 4 5 6 7 8 9 10
Sign in to vote for this snippet.

Comments:
(Please log in to write an comment.)