可以通过将 CheckForIllegalCrossThreadCalls 属性的值设置为 false 来禁用此异常。这会使控件以与在 Visual Studio 2003 下相同的方式运行。详见下面代码示例:
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 WindowsFormsApplication2 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { Form2.CheckForIllegalCrossThreadCalls = false;//不运行此句代码,将引发异常:线程间操作无效: 从不是创建控件“progressBar1”的线程访问它。 } private void button1_Click(object sender, EventArgs e) { progressBar1.Value = 0; ThreadStart ts = new ThreadStart(showProgress); Thread thread = new Thread(ts); thread.Start(); } private void showProgress() { for (int i = 0; i < progressBar1.Maximum; i++) { progressBar1.Value += 1; Thread.Sleep(100); } } } } |
|
来自: 蜗牛之窝 > 《WindowsForms》