首页 > Windows开发 > 详细

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

时间:2016-07-19 13:23:24      阅读:175      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!