C# Task 线程取消暂停

 为更好的理解我在此写成了窗体;

1.Task 线程操作

Winfrom UI 设计 

代码: 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Task_Cancellation
{
    public partial class Form1 : Form
    {
        private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
        private ManualResetEvent manualResetEvent = new ManualResetEvent(true);
        public Form1()
        {
            InitializeComponent();
        }

        void APPlinetext(string log)
        {
          BeginInvoke(new Action(() => {
                textBox1.AppendText(log);
            }));
        }
        private void button1_Click(object sender, EventArgs e)
        {
            _cancellationTokenSource =new CancellationTokenSource();
            manualResetEvent = new ManualResetEvent(true);
            int i = 0;
            Task.Run(() =>
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    manualResetEvent.WaitOne();
                    Thread.Sleep(300);
                    APPlinetext(string.Format("[线程:{0}]:第{1}次{2}", Environment.CurrentManagedThreadId, i++, Environment.NewLine));
                }

            },_cancellationTokenSource.Token);
        }

        private void button2_Click(object sender, EventArgs e)//暂停
        {
            manualResetEvent?.Reset();
        }

        private void button3_Click(object sender, EventArgs e)//继续
        {
            manualResetEvent?.Set();
        }

        private void button4_Click(object sender, EventArgs e)//停止
        {
            _cancellationTokenSource.Cancel();
        }
    }
}

2.Task异步带有返回值

//方法编程
public static async Task<int> Task1()
  {
    int op = 0;
    Console.WriteLine("无await:"+Environment.CurrentManagedThreadId + ":" + DateTime.Now.ToString("mm:ss:ff"));
    await Task.Run(() => {Thread.Sleep(1000); Console.WriteLine("第一个异步:"+Environment.CurrentManagedThreadId+":"+DateTime.Now.ToString("mm:ss:ff")); op++; });
    await Task.Run(() => { Thread.Sleep(1000); Console.WriteLine("第二个异步:" + Environment.CurrentManagedThreadId + ":" + DateTime.Now.ToString("mm:ss:ff")); op++; });
    return op;

  }
//调用方法
public static void Runtask()
{
    var ti = Task1();//异步开始
    Console.WriteLine("运行等待:" + Environment.CurrentManagedThreadId);
    Thread.Sleep(7000);//主线程等待
    Console.WriteLine("等待完毕:"+Environment.CurrentManagedThreadId);
    //Task.Result 会在运行完返回结果 期间主线程可以处理其他事务 后续进行Task 返回值判断
    Console.WriteLine("控制台打印:" + ti.Result + ":" + DateTime.Now.ToString("mm:ss:ff"));
    Console.WriteLine("运行完毕");
    Console.Read();
}

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值