parallel processing - Can i change and int value inside a task while its running? c# -


i learning how use tasks in c#, want able run 2 tasks @ same time. when first task ends. tell code stop second one. have tried many things none have worked, have tried:

  1. try looking related task.stop , have not found it. using task.wait first task when first 1 ends have stop second one.

  2. since second 1 infinite (its eternal loop) tried making parameter of loop change in main code, task method , variables in them unique.

tl;dr: want know if can change parameter inside task in order stop outside code. task take parameters? , can change them in main code after start running?

if none of previous things possible possible in way stop infinite task?

code:

task = new task(() => {     int sd = 3;      while (sd < 20)     {         console.write("peanuts");         sd++; //this can change cuz local task      } }); a.start(); // infinite task task b = new task(() =>  {     int s = 3; // parameter want change stop     while (s < 10)     {         console.write(s+1);      } }); b.start(); a.wait(); // here want stop task b  console.writeline("peanuts"); console.readkey(); 

try this:

public static void run() {     cancellationtokensource cts = new cancellationtokensource();     task1(cts);     task2(cts.token); }  private static void task2(cancellationtoken token) {     task.factory.startnew(() =>     {         int s = 3; // parameter want change stop                      while (!token.iscancellationrequested)         {             console.write(s + 1);         }     }, token); }  private static void task1(cancellationtokensource cts) {     task.factory.startnew(() =>     {         int sd = 3;          while (sd < 20)         {             console.write("peanuts");             sd++; //this can change cuz local task         }     }).continuewith(t => cts.cancel()); } 

cancellationtokensource cancelled when task1 finished. so, task2 checks cancellation token each iteration , exits infinite loop when cancellation requested.


Comments