2017-04-05 90 views
0

我目前正在学习如何在c#中使用任务,我希望能够同时运行2个任务。那么当第一个任务结束时。告诉代码停止第二个。我已经尝试了很多事情,但没有工作过,我曾尝试:运行时,我可以在任务内改变int值吗? c#

  1. 尝试寻找到task.stop相关的东西,并没有发现它。我正在使用task.wait进行第一个任务,所以当第一个任务结束时,我必须做一些事情来阻止第二个任务。因为第二个是无限的(它是一个永恒的循环)我试图使循环的参数,我可以在主代码中改变,但它像任务是一种方法,它们中的变量是唯一的。

TL; DR:我想知道是否可以在任务内改变一个参数,以阻止它从代码之外。做任务本身采取任何参数?我可以在开始运行后在主代码中更改它们吗?

如果以前的事情都不可能,那么可以以任何方式停止无限的任务吗?

CODE:

Task a = new Task(() => 
{ 
    int sd = 3; 
    while (sd < 20) 
    { 
     Console.Write("peanuts"); 
     sd++; //this i can change cuz its like local to the task 

    } 
}); 
a.Start(); 
// infinite task 
Task b = new Task(() => 
{ 
    int s = 3; // parameter i want to change to stop it 
    while (s < 10) 
    { 
     Console.Write(s+1); 

    } 
}); 
b.Start(); 
a.Wait(); 
// Now here I want to stop task b 

Console.WriteLine("peanuts"); 
Console.ReadKey(); 
+0

https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx – Dispersia

回答

0

试试这个:

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 i want to change to stop it 

        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 i can change cuz its like local to the task 
     } 
    }).ContinueWith(t => cts.Cancel()); 
} 

CancellationTokenSource将在任务1结束被取消。因此,任务2每次迭代都会检查取消标记,并在请求取消时退出无限循环。

相关问题