Link to home
Start Free TrialLog in
Avatar of fixitben
fixitben

asked on

C# abort a thread

Hi

I am new to working with threads. I have something that runs under a thread that just scans for projects and makes sure the folder path exists.

I start it using
Thread th =  new Thread(() =>
           {
                CheckProjects();
            });
th.Start();

Open in new window


I tried running

th.Abort();

Open in new window

But that doesn't stop the thread from running.

Is there an easy way to kill that thread? I have a cancel button I would like to use to stop it if needed for some reason mid scan.

Thanks
Fixitben
ASKER CERTIFIED SOLUTION
Avatar of Nadav Solomon
Nadav Solomon

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of it_saige
Which .NET version are you using?  If you are using .NET 4 or above, it is more preferable to use Tasks as opposed to Threads directly.  The reason I mention this is because Tasks can be configured to include a cancellation token.

Proof of concept -
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace EE_Q28761679
{
	class Program
	{
		static void Main(string[] args)
		{
			CancellationTokenSource source = new CancellationTokenSource();
			CancellationToken token = source.Token;
			Task<long> task = new Task<long>(() => 
			{
				Stopwatch watch = new Stopwatch();
				watch.Start();
				while (!token.IsCancellationRequested) { ;}
				watch.Stop();
				return watch.ElapsedMilliseconds;
			}, token);
			task.Start();
			Console.WriteLine("Press any key to stop the task");
			Console.ReadLine();
			source.Cancel();
			Console.WriteLine("Task ran for {0} milliseconds...", task.Result);
			Console.ReadLine();
		}
	}
}

Open in new window

Which produces the following output -User generated imageUser generated image-saige-
Avatar of fixitben
fixitben

ASKER

Thanks. This worked great. It took me a little bit to figure out where in the code to place it, but then it works like a charm.
Glad I could help, thanks for the feedback.