zoukankan      html  css  js  c++  java
  • C#中多线程实现后台任务的三种方式

    第一种:通过Invoke()在应用程序的主线程上执行指定的委托

    //新开一个线程,显示当前时间
    new Thread(o =>
    {                
        while (true)
        {
            Thread.Sleep(1000);
            Invoke((Action)delegate
            {
                this.textBox1.Text= DateTime.Now.ToString();
            }); 
        }
    })
    { IsBackground = true }.Start();

    第二种:使用类BackgroundWorker

    //声明后台工作对象
    BackgroundWorker BgWork = new BackgroundWorker();
    //绑定事件
    private void Form1_Load(object sender, EventArgs e)
    {
        BgWork.DoWork += BgWork_Demo;
        BgWork.RunWorkerAsync();
    }            
    //要后台执行的函数        
    void BgWork_Demo(object sender, DoWorkEventArgs e)
    {
        try
        {
            Random rd = new Random();
            int i=rd.Next(1,3);
            if (i=1)
            {
                this.Invoke((EventHandler)(delegate { this.textBox1.Text = "成功就行怀孕,大家都会恭喜你!"; }));
            }
            else
                this.Invoke((EventHandler)(delegate { this.textBox1.Text = "但是没有人知道《你被搞了》多少遍才成功!"; }));
        }
        catch (Exception ex)
        {
            MessageBox.Show("程序出来点小问题..." + ex.Message, "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
        }
    }

    第三种:使用一个Timer结合异步委托方法

    Timer tm = new Timer();
    private void Form_Load(object sender, EventArgs e)
    {
        tm.Interval = 1000;
        tm.Tick += tm_Tick;
        this.BeginInvoke((EventHandler)(delegate { tm.Start(); }));
    }
    
    void tm_Tick(object sender, EventArgs e)
    {    
        if (1 == 2)
        {
            tm.Stop();        
            //do something...
        }
    }

    今天的知识就到这里啦,学会了没有。

    凡哥,别他妈吹牛逼了
  • 相关阅读:
    Atcoder Beginner Contest075 翻车记
    bzoj1972 猪国杀 大♂模拟
    10月9-11日连续大翻车实录
    10月8日翻车实录
    10月7日考试翻车实录
    四月は君の嘘?人生は君の嘘?
    NOIP模拟 gcd 数学
    NOIP模拟 water 最小生成树
    NOIP模拟 mine DP
    bzoj2064 分裂 状压DP
  • 原文地址:https://www.cnblogs.com/sdlz/p/15011914.html
Copyright © 2011-2022 走看看