C#的WinForm多线程应用

VS2005环境下,新建一个window窗体:命名多线程应用

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace 多线程应用
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;//这种方法不好,最好用委托
            InitializeComponent();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            txtOutput.Text = "0";
            lstMessage.Items.Clear();
            int threadNumber = Convert.ToInt32(this.txtThreadNumber.Text);
            for (int i = 1; i <= threadNumber; i++)
            {
                //ThreadStart threadStart = new ThreadStart(Add);
                Thread thread = new Thread(new ThreadStart(this.Add));
                thread.Name = i.ToString();
                thread.Start();
            }
        }
        private void Add()
        {
            DateTime beginTime = DateTime.Now;
            long minValue = long.Parse(txtMinValue.Text);
            long maxValue = long.Parse(txtMaxValue.Text);
            int threadNumber = Convert.ToInt32(txtThreadNumber.Text);
            int threadOrder = Convert.ToInt32(Thread.CurrentThread.Name);
            long step=(maxValue-minValue+1)/threadNumber;
            long beginValue=minValue+step*(threadOrder-1);
            long endValue = beginValue + step;
            long result = 0;
            for (long i = beginValue; i < endValue; i++)
            {
                result += i;
            }
            lock(this)//线程同步锁
            {
                long sum = long.Parse(txtOutput.Text);
                sum += result;
                txtOutput.Text = sum.ToString();
            }
            DateTime endTime = DateTime.Now;
            TimeSpan timeSpan = endTime - beginTime;
            string message = "线程" + Thread.CurrentThread.Name + ":" + beginValue.ToString() + "到" + endValue.ToString() + ",耗时:" + timeSpan.TotalMilliseconds.ToString() + "毫秒";
            this.lstMessage.Items.Add(message);
            Thread.CurrentThread.Abort();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

总结:

多线程虽然可以提高程序的运行效率,但也不是绝对的,效率不会随线程数目增加呈现线性提高的,大家适当运用,另外下次我会用委托解决一些多线程的问题哦

转载于:https://www.cnblogs.com/zwq194/archive/2008/11/23/1339596.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值