c# - 如何在 C# 中重新启动 System.Threading.Tasks.Task

标签 c# .net multithreading task

我正在开发一个应用程序,其中的任务可以稍后停止并重新启动。 为此我有两种方法:

public static void TaskProcess()
    {
        var tokenSource = new CancellationTokenSource();
        CancellationToken token = tokenSource.Token;
        var task = new Task(
            () =>
                {
                    DoWork(token);
                }, 
            token);

        task.ContinueWith(
            task1 =>
                {
                    Console.WriteLine("Task finished... press any key to continue");
                    Console.ReadKey();
                    Console.WriteLine("Press q to quit...");
                },
            token);

        task.Start();

        string input;
        while ((input = Console.ReadLine()) != "q")
        {
            if (input == "c")
            {
                tokenSource.Cancel();
            }
            if (input == "r")
            {
                if (task.IsCompleted)
                {
                    // Here i want to restart my completed task
                }
                else
                {
                    Console.WriteLine("Task is not completed");
                }
            }
        }
    }

    private static void DoWork(CancellationToken token)
    {
        int i = 0;
        while (true)
        {
            i++;
            Console.WriteLine("{0} Task continue...", i);
            Thread.Sleep(1000);

            if (token.IsCancellationRequested)
            {
                Console.WriteLine("Canceling");
                token.ThrowIfCancellationRequested();
            }
        }
    }

目前,我创建了 Task 和 CancellationToken 的新实例来“重新启动”任务,但如果可能的话,我正在寻找更好的东西:

if (input == "r")
            {
                if (task.IsCompleted)
                {
                    Console.WriteLine("Task is completed... Restarting");
                    tokenSource = new CancellationTokenSource();
                    token = tokenSource.Token;
                    CancellationToken token1 = token;
                    task = new Task(
                        () => DoWork(token1),
                        token);
                    task.Start();
                }
                else
                {
                    Console.WriteLine("Task is not completed");
                }
            }

感谢您的帮助。

最佳答案

不,TaskTaskCancellationSource 是 use 和 throw 对象。你不能重复使用它们。您必须像当前一样创建新对象。

这是有道理的,假设您已经取消了一个任务,稍后在某个时刻,一些代码需要检查任务的状态。在您重新启动任务后不久(不可能,为了解释而说),告诉已经已取消任务的状态为正在运行是否会产生误导?

关于c# - 如何在 C# 中重新启动 System.Threading.Tasks.Task,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26161849/

相关文章:

c# - 使用对象以外的东西锁定线程

c# - 对通过 XmlWriter 输出的函数进行单元测试?

.net - 为暴露给 COM 的 .NET 类定义接口(interface)有什么好处?

c# - 通过 MSI 安装后可执行文件未签名

multithreading - Scala List的cons运算符 “::”是线程安全的吗?

python - 运行 python 并行进程

c# - 异常和返回语句是 C# 中唯一可能的提前退出吗?

c# - C# 中的 Skype 插件

c# - 从什么类型的时间中获取现在是白天还是夜晚

c++ - 如何使用#include <thread> 编译代码