首页 > Web开发 > 详细

net4.0 task 超时任务代码 用Thread.sleep方式实现

时间:2017-02-06 14:32:44      阅读:195      评论:0      收藏:0      [点我收藏+]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
namespace WindowsFormsApplication2
{   delegate void invokeDelegate();
    public partial class Form1 : Form
    {
        CancellationTokenSource ts = new CancellationTokenSource();

        public Form1()
        {
            InitializeComponent();


        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "AAA");
            var invokeThread = new Thread(new ThreadStart(StartMethod));
            invokeThread.Start();
            string a = string.Empty;
            for (int i = 0; i < 5; i++)      //调整循环次数,看的会更清楚
            {
                Thread.Sleep(1000);
                a = a + "B";
            }
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + a);
        }

        private void StartMethod()
        {
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "CCC");
            button1.Invoke(new invokeDelegate(invokeMethod));
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "DDD");
        }

        private void invokeMethod()
        {
            Thread.Sleep(3000);
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "EEE");
        }


        private void lableeeidt(string text)
        {
    
            
            if (label1.InvokeRequired)
            {
                label1.Invoke(new Action<string>(lableeeidt),text);
            }
            label1.Text = text;

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        
        private void button2_Click(object sender, EventArgs e)
        {
            Task task = new Task(() =>
            {  int i=0;
                while (!ts.IsCancellationRequested)
                {  i++;
                    lableeeidt(i.ToString());
                    Thread.Sleep(1000);

                }


            },ts.Token);

            task.Start();
            //新开一个task任务,里面用sleep实现超时
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(4500);
                ts.Cancel();
            });
       
            
           
        }
    }
}

 

net4.0 task 超时任务代码 用Thread.sleep方式实现

原文:http://www.cnblogs.com/daming1233/p/6369899.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!