码迷,mamicode.com
首页 > Windows程序 > 详细

[C#][.net 4]Task 代码示例

时间:2016-07-19 13:23:33      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestApplication1
{
    public partial class Form2 : Form
    {
        delegate void CountEventHandler(object sender, int count);
        CancellationTokenSource tokenSource;
        CancellationToken token;

        public Form2()
        {
            InitializeComponent();
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            tokenSource = new CancellationTokenSource();
            token = tokenSource.Token;
            Task.Factory.StartNew(Run, token);
        }

        void Run()
        {
            long rCount = Convert.ToInt64(textBox1.Text);
            for (int i = 0; i < rCount; i++)
            {
                CountChange(null, i);
            }
        }

        private void CountChange(object sender, int i)
        {
            if (token.IsCancellationRequested)
                return;
            if (textBox2.InvokeRequired)
            {
                textBox2.Invoke(new CountEventHandler(CountChange), sender, i);
            }
            else
            {
                textBox2.Text = i.ToString();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            tokenSource.Cancel();
        }
    }
}

button1 > 启动 button2 > 停止 textBox1 > 总循环次数 textBox2 > 当前计数

[C#][.net 4]Task 代码示例

标签:

原文地址:http://www.cnblogs.com/z5337/p/5684128.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!