控制任务的开始,停止和重新启动

我想创建一个循环连接检查任务(在连接启动后启动)这两个函数都可以工作,但我不知道如何重新启动之前执行的任务。 基本上这是我想要实现的:

创建任务循环

我只能直接启动任务,任何尝试创建任务并稍后执行都会失败。 还重新启动先前执行的任务失败。 任何人都可以帮助我,是否有可能实现我的目标? 如果是的话,这是正确的方向,还是我做结构错误? 这让我烦恼几天,任何帮助或提示将不胜感激。

class Program
{       
    static void Main(string[] args)
    {       
        Task<ReturnResult> ConnectionStartResult = CommManager.StartAllConnections();
        Task<List<ReturnResult>> ConnectionCheckResult = CommManager.CreateConnectionCheckTask();
        //Task<List<ReturnResult>> ConnectionCheckResult = CommManager.StartConnectionCheck();

        ConnectionStartResult.ContinueWith((prevTask) =>
        {
            CommManager.ValueListerStart();
            //ConnectionCheckResult.Start();
        });

        ConnectionCheckResult.ContinueWith((myPreviusTask) =>
        {
            CommManager.ValueListerStop();
            Console.WriteLine("Connection problems found");
            ConnectionStartResult = CommManager.StartAllConnections();
        });
    }
}


public class CommManager
{
    private static CancellationTokenSource CommCheckTokenSource;

    // starts connections in the background, end when done
    public static async Task<ReturnResult> StartAllConnections()
    {
        ReturnResult result = await Task.Run(() => ConnectAll());
        return result;
    }

    private static ReturnResult ConnectAll()
    {
        Thread.Sleep(1000);
        return new ReturnResult();
    }

    // start and run connection check. Works, but i cannot recall this after connection problem 
    public static async Task<List<ReturnResult>> StartConnectionCheck()
    {
        CommCheckTokenSource = new CancellationTokenSource();
        var CommCheckToken = CommCheckTokenSource.Token;
        return await Task.Run(() => CheckPlcConnectionsTask(CommCheckToken));
    }

    // only create task. (but do not start) works but locks up the UI thread, whan started in main
    public static Task<List<ReturnResult>> CreateConnectionCheckTask()
    {
        CommCheckTokenSource = new CancellationTokenSource();
        var CommCheckToken = CommCheckTokenSource.Token;
        return new Task<List<ReturnResult>>(() => CheckPlcConnectionsTask(CommCheckToken));
    }        

    // the connection check function
    private static List<ReturnResult> CheckPlcConnectionsTask(CancellationToken token)
    {
        var returnList = new List<ReturnResult>();
        while (!token.IsCancellationRequested)
        {
            // keep checking connection only return when disconnect is found
            Thread.Sleep(3000);  // for test
            return returnList;
        }
        return returnList;
    }


    public static void ValueListerStart()
    { }

    public static void ValueListerStop()
    { }
}

public class ReturnResult
{ }
链接地址: http://www.djcxy.com/p/52805.html

上一篇: Control the start, stop and restart of tasks

下一篇: c# multiple tasks do not run in parallel