A)
You could try this approach:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
class Program
{
static long counter = 0;
static void DoLongRunningTask(CancellationToken token)
{
token.ThrowIfCancellationRequested();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
Console.Write("{0}\r",counter++);
if (token.IsCancellationRequested)
{
stopwatch.Stop();
Console.WriteLine("\nCanceled. Cleaning up. Time elapsed: {0}", stopwatch.Elapsed);
token.ThrowIfCancellationRequested();
}
}
}
static void Main()
{
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
var task = new Task(() => DoLongRunningTask(token), token);
Console.Write("Task ");
task.Start();
tokenSource.CancelAfter(10000);
Console.Write("started and should run 10 seconds\n");
try { task.Wait(); }
catch { }
Console.WriteLine("Status: {0}", task.Status);
Console.WriteLine("IsCanceled: {0}", task.IsCanceled);
Console.WriteLine("IsCompleted: {0}", task.IsCompleted);
task.Dispose();
Console.WriteLine("Finished. Press any key.");
Console.ReadKey();
}
}
Please note, that this is no brute-force cancellation. It won't "kill" the task, it requires neat finishing. So if you are blocked inside one operation - let's call it atomic in this sense -, this won't help you. (Source:
http://www.blackwasp.co.uk/TaskCancellation_2.aspx[
^])
You can however not wait in this manner for the task to complete, you could do anything else in your service in the meantime.
An interesting article, but I couldn't get it working in a few minutes:
http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235834.aspx[
^]
B)
Using workers:
http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx[
^]
C)
For threading, you could use this approach:
http://dotnet-snippets.com/snippet/end-thread-after-timeout/656[
^], however you have top be careful with aborting treads. (see also:
http://msdn.microsoft.com/en-us/library/5b50fdsz.aspx[
^])
Anyway, you should be very careful with cleaning your resources when you stop such an execution.