zoukankan      html  css  js  c++  java
  • C#多线程实例(C#反应慢时 加个进度条)

    using System.Threading;

    namespace Threading
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    BackgroundWorker back = null;
    Thread thread = null;
    Form2 f2 = null;
    private void button1_Click(object sender, EventArgs e)
    {
    back = new BackgroundWorker();
    back.WorkerSupportsCancellation = true;
    back.DoWork += new DoWorkEventHandler(back_DoWork);
    back.RunWorkerCompleted += new RunWorkerCompletedEventHandler(back_RunWorkerCompleted);
    back.RunWorkerAsync();

    //显示进度条 窗体
    f2 = new Form2();
    f2.BgWorker = thread;
    f2.ShowDialog();
    }

    void back_DoWork(object sender, DoWorkEventArgs e)
    {

    thread = Thread.CurrentThread;
    e.Result = Func();// 方法里面的操作;//数据查询操作写这里,就是你比较慢的操作写这里 这里最好不要出现控件
    }

    void back_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    if (e.Result != null)
    {
    if (f2 != null)
    {
    f2.Close();
    }

    if (thread != null)
    {
    thread = null;
    }
    //查询出来的数据在这里显示 ---- 显示的时候也会卡一下的
    //e.Result 转换成DoWorker事件中传过来的类型
    // MessageBox.Show(e.Result.ToString());
    }
    }

    private string Func()
    {
    string str = String.Empty;
    for (int i = 0; i < 30000; i++)
    {
    str += i.ToString();

    }
    return str;
    }
    }

    显示进度条窗体

    using System.Threading;


    namespace Threading
    {
    public partial class Form2 : Form
    {
    public Form2()
    {
    InitializeComponent();
    }
    private Thread worker = null;

    public Thread BgWorker
    {
    get { return worker; }
    set { worker = value; }
    }

    private void Form2_Load(object sender, EventArgs e)
    {
    this.progressBar1.Style = ProgressBarStyle.Marquee; //进度条
    }



    private void button1_Click_1(object sender, EventArgs e)
    {
    if (worker != null)
    {
    worker.Abort(); // 结束进程
    }
    this.Close();
    }

    private void Form2_FormClosing_1(object sender, FormClosingEventArgs e)
    {
    if (worker != null)
    {
    worker.Abort();
    }
    }

    }
    }



  • 相关阅读:
    Codeforces 931A&1312A&172A
    STL常用容器(deque&stack&queue)
    Codeforces 141A&1368A
    Tensorflow安装和配置
    Spark高可用配置
    Spark安装及环境配置
    SSH免密登录
    大数据集群linux环境搭配
    Spark学习之RDD算子
    Spark学习之再谈RDD
  • 原文地址:https://www.cnblogs.com/laojiefang/p/2387278.html
Copyright © 2011-2022 走看看