0

I have a problem with canceling task in c#, task[0] does not stop executing. Here is the code.

 var tokenSource = new CancellationTokenSource();
 var token = tokenSource.Token;
 Task[] tasks = new Task[2];
 tasks[0] = Task.Run(() => {
 SomeClass Object1  = new SomeClass();
    if (tasks[1].IsCompleted)
    {
        tokenSource.Cancel();
    }
 },token);
 tasks[1] = Task.Run(() =>
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Form1());
 });
Zong
  • 6,160
  • 5
  • 32
  • 46
Mac
  • 307
  • 3
  • 8
  • 18
  • Possible duplicate of [How to cancel a Task in await?](http://stackoverflow.com/questions/10134310/how-to-cancel-a-task-in-await) – Claudius Apr 28 '16 at 19:19
  • It's worth pointing out that we cant see what code the other tasks are running, and simply calling `CancellationTokenSource.Cancel()` doesn't actually cancel anything, it's incumbent on the executing task to check the token and act on a cancellation request. – CodingGorilla Apr 28 '16 at 19:27
  • You never start `tasks[1]` so of course it won't be complete. Secondly, even if you *do* start `tasks[1]`, it would have to almost immediately complete if it were to be marked as `IsCompleted` by the time `tasks[0]` starts. – Rob Apr 29 '16 at 00:21

2 Answers2

1

Firstly, you should run tasks[1];

Secondly, you should check if task[1] is completed in a loop and return from task, you don't need CancellationToken in your example:

Task[] tasks = new Task[2];

// run task[1]

tasks[0] = Task.Run(() => {
    SomeClass Object1  = new SomeClass();
    while (true)
    {
        if(tasks[1].IsCompleted)
        {
            return;
        }
    }

},token);  
Roman
  • 11,966
  • 10
  • 38
  • 47
0

I solved the problem, simply added "Task.WaitAll(tasks[1]);" at the end of the code.

         Task[] tasks = new Task[2];

         tasks[0] = Task.Run(() => 
         {
         SomeClass Object1  = new SomeClass();
            if (tasks[1].IsCompleted)
            {
                tokenSource.Cancel();
            }
         });
         tasks[1] = Task.Run(() =>
         {
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);
             Application.Run(new Form1());
         });

        Task.WaitAll(tasks[1]);

Thanks everyone for input.

Mac
  • 307
  • 3
  • 8
  • 18