本帖最后由 lgh521911 于 2013-9-24 22:59 编辑
刚刚开始接触线程就碰壁了,还请大家多多指教。问题如代码。- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Threading;
- namespace 课堂练习1
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- /// <summary>
- /// 单线程的缺点
- /// 验证单线程在运行时的状态
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void button1_Click(object sender, EventArgs e)
- {
- count();
- }
- /// <summary>
- /// 循环计数的方法(创建一个count类来接收数据)
- /// </summary>
- void count()
- {
- DateTime beginTime = DateTime.Now;
- for (double i = 0; i <999999999; i++)
- {
- }
- TimeSpan ts = beginTime.Subtract(DateTime.Now);
- MessageBox.Show("循环完毕"+ts.TotalMilliseconds);
- }
- /// <summary>
- /// 使用多线程来解决 UI卡死
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btnnum2_Click(object sender, EventArgs e)
- {
- //创建线程对象 传入要线程执行的方法;
- Thread threadFirst = new Thread(count);
- //将线程设置为后台线程(当所有的前台线程结束后,后台线程会自动退出)
- threadFirst.IsBackground = true;
- //启动线程 执行方法
- threadFirst.Start();
- }
- /// <summary>
- /// 修改文本框中的内容
- /// </summary>
- void changeTxt()
- {
- for (int i = 0; i < 1000; i++)
- {
- int a = int.Parse(txtNum.Text); //边看边练,我的输入都没错误,为什么到这里和视频教学里的错误不一样?(附图)
- a++;
- txtNum.Text = a.ToString();
- }
- }
- private void txtnum_TextChanged(object sender, EventArgs e)
- {
- }
- private void btnproblem_Click(object sender, EventArgs e)
- {
- Thread threadProblem = new Thread(changeTxt);
- threadProblem.IsBackground = true;
- threadProblem.Start();
- }
- }
- }
复制代码 为什么与教学视频中弹出的问题不一样? |
|