【问题标题】:Can i change and int value inside a task while its running? c#我可以在任务运行时更改任务内部的值吗? C#
【发布时间】:2017-04-05 21:49:54
【问题描述】:

我目前正在学习如何在 c# 中使用任务,我希望能够同时运行 2 个任务。然后当第一个任务结束时。告诉代码停止第二个。我尝试了很多东西,但都没有奏效,我试过了:

  1. 尝试查找与 task.stop 相关的内容,但没有找到。我正在使用 task.wait 来完成第一个任务,所以当第一个任务结束时,我必须做一些事情来停止第二个任务。

  2. 1234563

TL;DR:我想知道我是否可以更改任务内部的参数以阻止它在其代码之外进行。任务本身是否带有任何参数?我可以在它们开始运行后在主代码中更改它们吗?

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

代码:

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();

【问题讨论】:

标签: c# parallel-processing int task


【解决方案1】:

试试这个:

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 将在 Task1 完成后取消。因此,Task2 每次迭代都会检查取消令牌,并在请求取消时退出无限循环。

【讨论】:

    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    相关资源
    最近更新 更多