调试高手请进, 多线程程序一运行就崩溃?

hisense2423 2008-04-23 08:49:06
各位,
下面这段代码是我学习多线程时的一段代码,程序的目的就是创建两个线程,让他们同时运行,并把结果在主窗体的列表控件框中更新,但是我这个程序怎么一调试运行的时候就崩溃啊,是不是我哪里使用错了,希望各位不吝赐教。




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

namespace SimpleEx
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class MainApp : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox lbResult;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

public MainApp()
{
InitializeComponent();
DoSample();
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.lbResult = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// lbResult
//
this.lbResult.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbResult.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbResult.ItemHeight = 14;
this.lbResult.Location = new System.Drawing.Point(0, 0);
this.lbResult.Name = "lbResult";
this.lbResult.Size = new System.Drawing.Size(292, 270);
this.lbResult.TabIndex = 0;
//
// MainApp
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.lbResult);
this.Name = "MainApp";
this.Text = "多线程的简单实例";
this.ResumeLayout(false);

}
#endregion

private void DoSample()
{
// Thread thread1 = new Thread(new ThreadStart( Count));
// thread1.Name="线程一";
// Thread thread2 = new Thread(new ThreadStart( Count));
// thread2.Name="线程二";
// thread1.Start();
// thread2.Start();

Thread t1 = new Thread(new ParameterizedThreadStart(ParamCount));
t1.Name = "T1";
t1.Start(this);

Thread t2 = new Thread(new ParameterizedThreadStart(ParamCount));
t2.Name = "T2";

t2.Start(this);
}

private void Count()
{
for (int i=0;i<=5;i++)
{
lbResult.Items.Add(Thread.CurrentThread.Name + "数到" + i);
Thread.Sleep(1000);
}

}

private void ParamCount(object obj)
{
MainApp mainThread = (MainApp)obj;

for (int i = 0; i <= 5; i++)
{
mainThread.lbResult.Items.Add(Thread.CurrentThread.Name +" count "+ i);
Thread.Sleep(100);
}
}

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new MainApp());
}
}
}
...全文
206 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
fly_to_sky 2008-04-23
  • 打赏
  • 举报
回复
其实我也遇到过这样的问题,也搞不清究竟是什么问题!运行好好的,调试总是报一些乱七八糟的错,是不是我们触犯了bug!呵呵
孤剑 2008-04-23
  • 打赏
  • 举报
回复
try...catch ...找错误。

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧