zoukankan      html  css  js  c++  java
  • 多线程

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace 多线程
    {
        public partial class Form1 : Form
        {
            private CancellationTokenSource cts;
            public Form1()
            {
                InitializeComponent();
            }
            private void CountTo(int countTo, CancellationToken ct)
            {
                int sum = 0;
                for (; countTo > 0; countTo--)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }
                    sum += countTo;
                    //Invoke方法用于获得创建lbl_Status的线程所在的上下文
                    this.Invoke(new Action(() => textBox1.Text = sum.ToString()));
                    Thread.Sleep(200);
                }
            }
            private void button1_Click(object sender, EventArgs e)
            {
                cts = new CancellationTokenSource();
                ThreadPool.QueueUserWorkItem(state => CountTo(int.Parse(textBox2.Text), cts.Token));
            }
            private void button2_Click(object sender, EventArgs e)
            {
                if (cts != null)
                {
                    cts.Cancel();
                }              
            }
        }
    }
    多线程解决界面卡顿问题

    说明:将方法排入队列以便执行,WaitCallback,表示要执行的方法。如果将方法成功排入队列,则为 true;否则为 false

    示例:addtest方法需要比较长的时间来响应,因此在button1_Click被点击以后,程序会失去响应,使用ThreadPool.QueueUserWorkItem 后,页面会继续响应其他时间,等addtest执行结束后,响应结果。


    using
    System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace 多线程 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }private void button1_Click(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(new WaitCallback(addtest), "Testaa"); }private void addtest(object aa) { long result = 0; for (int i = 0; i < 1000000000; i++) { result += i; } textBox1.Text = result.ToString() + "HELLO"; } } }
  • 相关阅读:
    python ping监控
    MongoDB中一些命令
    进制转换(十进制转十六进制 十六进制转十进制)
    通过ssh建立点对点的隧道,实现两个子网通信
    linux环境下的各种后台执行
    python requests请求指定IP的域名
    不需要修改/etc/hosts,curl直接解析ip请求域名
    MongoDB数据update的坑
    windows平台使用Microsoft Visual C++ Compiler for Python 2.7编译python扩展
    rabbitmq问题之HTTP access denied: user 'guest'
  • 原文地址:https://www.cnblogs.com/772933011qq/p/5095314.html
Copyright © 2011-2022 走看看