Task 开始 停止
阅读原文时间:2023年07月11日阅读:1

注意点:需要将每个线程的 MemoryCacheManager 保存,这里我保存在缓存中,需要取消时根据缓存key值取出 MemoryCacheManager

    //开始Task1  
    private void button1\_Click(object sender, EventArgs e)  
    {  
        CheckForIllegalCrossThreadCalls = false;//winform运行跨线程

        ICacheManager cacheManager = new MemoryCacheManager();  
        var cts1 = new CancellationTokenSource();  
        CancellationToken ct1 = cts1.Token;  
        Task.Factory.StartNew(() =>  
        {  
            while (true)  
            {  
                Thread.Sleep();  
                listView1.Items.Add("AA当前时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));  
                if (ct1.IsCancellationRequested)  
                {  
                    // another thread decided to cancel  
                    listView1.Items.Add("task1 canceled");  
                    cacheManager.Remove("cts1");  
                    break;  
                }  
            }  
        }, ct1);

        if (!cacheManager.IsSet("cts1"))  
        {  
            cacheManager.Set("cts1", cts1, );  
        }  
    }

    //开始Task2  
    private void button2\_Click(object sender, EventArgs e)  
    {  
        CheckForIllegalCrossThreadCalls = false;//winform运行跨线程

        ICacheManager cacheManager = new MemoryCacheManager();  
        var cts2 = new CancellationTokenSource();  
        CancellationToken ct2 = cts2.Token;  
        Task.Factory.StartNew(() =>  
        {  
            while (true)  
            {  
                Thread.Sleep();  
                listView1.Items.Add("BB当前时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));  
                if (ct2.IsCancellationRequested)  
                {  
                    // another thread decided to cancel  
                    listView1.Items.Add("task1 canceled");  
                    cacheManager.Remove("cts2");  
                    break;  
                }  
            }  
        }, ct2);

        if (!cacheManager.IsSet("cts2"))  
        {  
            cacheManager.Set("cts2", cts2, );  
        }  
    }

    //停止Task1  
    private void button3\_Click(object sender, EventArgs e)  
    {  
        ICacheManager cacheManager = new MemoryCacheManager();  
        var cts = cacheManager.Get<CancellationTokenSource>("cts1");  
        cts.Cancel();  
    }

    //停止Task2  
    private void button4\_Click(object sender, EventArgs e)  
    {  
        ICacheManager cacheManager = new MemoryCacheManager();  
        var cts = cacheManager.Get<CancellationTokenSource>("cts2");  
        cts.Cancel();  
    }

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章