public Form1()
{
InitializeComponent();
th = new Thread(new ThreadStart(run));
}
Thread th ;
public void run()
{
while (this.progressBar1.Value<=99)
{
this.progressBar1.Increment(1);
Thread.Sleep(50);
}
}
private void button1_Click(object sender, EventArgs e)
{
th.Start();
} private void button2_Click(object sender, EventArgs e)
{
this.progressBar1.Value = 0;
th.Abort();
}点开始 在点停止 在点开始就报错
{
InitializeComponent();
th = new Thread(new ThreadStart(run));
}
Thread th ;
public void run()
{
while (this.progressBar1.Value<=99)
{
this.progressBar1.Increment(1);
Thread.Sleep(50);
}
}
private void button1_Click(object sender, EventArgs e)
{
th.Start();
} private void button2_Click(object sender, EventArgs e)
{
this.progressBar1.Value = 0;
th.Abort();
}点开始 在点停止 在点开始就报错
解决方案 »
- 非泛型集合ArrayList和泛型集合List,运行时间问题
- 新手求教,winform之间获取控件的问题?在线等!!
- 求一正则表达式写法
- 怎样获得动态二维数组的行数?
- 急!急!急!datagridview 中记住行的值(在线等)
- 为什么按键没反应呢?高手帮忙了!
- C#编写局域网程序
- 在C#中使用javascript的问题.!!!????
- 好久不做 ado.net,,到底该用IDataReader还是DbDataReader?????
- 数据库连接一般是应该放在哪一个方法或类下面
- 在C#2005winform中,文本输入框的得到焦点事件是哪个?
- Winform上的一个listbox,在designer上绑定了DB的一个表,当表中数据更新后,如何使用最少代码让listbox能自动更新?
后加一句:th.IsBackground = true;
这里应该用Invoke.不然调试的时候会出错.
这样就行了,代码很拙劣
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
{
Thread th;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false; //...
} private void button1_Click(object sender, EventArgs e)
{
th = new Thread(new ThreadStart(run));
th.Start();
} private void button2_Click(object sender, EventArgs e)
{
this.progressBar1.Value = 0;
th.Abort();
}
public void run()
{
while (this.progressBar1.Value <= 99)
{
this.progressBar1.Increment(1);
Thread.Sleep(50);
}
} }
}
Windows 窗体控件本质上不是线程安全的。如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态。还可能出现其他与线程相关的 bug,包括争用情况和死锁。确保以线程安全方式访问控件非常重要。 .NET Framework 有助于在以非线程安全方式访问控件时检测到这一问题。在调试器中运行应用程序时,如果创建某控件的线程之外的其他线程试图调用该控件,则调试器会引发一个 InvalidOperationException,并提示消息:“从不是创建控件 control name 的线程访问它。” 此异常在调试期间和运行时的某些情况下可靠地发生。强烈建议您在显示此错误信息时修复此问题。在调试以 .NET Framework 2.0 版之前的 .NET Framework 编写的应用程序时,可能会出现此异常。 可以通过将 CheckForIllegalCrossThreadCalls 属性的值设置为 false 来禁用此异常。
用BackgroundWorker组件吧 具体怎么用 MSDN