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...
        }
    }

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

    凡哥,别他妈吹牛逼了
  • 相关阅读:
    hdu 1028 Ignatius and the Princess III (n的划分)
    CodeForces
    poj 3254 Corn Fields (状压DP入门)
    HYSBZ 1040 骑士 (基环外向树DP)
    PAT 1071 Speech Patterns (25)
    PAT 1077 Kuchiguse (20)
    PAT 1043 Is It a Binary Search Tree (25)
    PAT 1053 Path of Equal Weight (30)
    c++ 常用标准库
    常见数学问题
  • 原文地址:https://www.cnblogs.com/sdlz/p/15011914.html
Copyright © 2011-2022 走看看