以文本方式查看主题 - 计算机科学论坛 (http://bbs.xml.org.cn/index.asp) -- 『 Dot NET,C#,ASP,VB 』 (http://bbs.xml.org.cn/list.asp?boardid=43) ---- 解决线程访问控件时产生的 CrossThread 方法 (http://bbs.xml.org.cn/dispbbs.asp?boardid=43&rootid=&id=122133) |
-- 作者:卷积内核 -- 发布时间:10/20/2011 9:07:00 AM -- 解决线程访问控件时产生的 CrossThread 方法 Windows Forms 控件通常不是thread-safe(直接或间接继承于System.Windows.Forms.Control),因此.NET Framework为防止multithread下对控件的存取可能导致控件状态的不一致,在调试时,CLR-Debugger会抛出一个InvalidOperationException以‘建议‘程序员程序可能存在的风险。 问题的关键在于,动机是什么?和由此而来的编程模型的调整。 1. Example首先,看一个代码实例。该例要完成的工作是由一个Button的Click触发,启动一个Thread(Manual Thread),该Thread的目的是完成设置TextBox的Text’s Property。 1.1 Unsafe access to control Code 1.1 using System; using System.Configuration; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void unsafeSetTextButton_Click(object sender, EventArgs e) { Thread setTextThread = new Thread(new ThreadStart(doWork)); setTextThread.Start(); } private void doWork() { string fileName = ".\\test-src.txt"; if (!File.Exists(fileName)) { MessageBox.Show(string.Format("{0} doesn't exist!", fileName), "FileNoFoundException"); return; } string text = null; using (StreamReader reader = new StreamReader(fileName, Encoding.Default)) { text = reader.ReadToEnd(); } this.textBox1.Text = text; } } } 在调试时,CLR-Debugger会在以上代码中粗体处将会弹出 提示说,当前存取控件的thread非创建控件的thread(Main Thread)。 |
-- 作者:卷积内核 -- 发布时间:10/20/2011 9:08:00 AM -- how to access a control from another thread which didn't create this control. I faced this issue more than 1 time, I decided to collect info about it and made some changes on the code to simplify this problem to you cause it's really annoying and confusing to work with threading stuff. Here is a small code solves this problem FOREVER and in ANY case. Error: Cross thread operation not valid: Control "XXXXXXXXXX" accessed from a thread other than the thread it was created. Solution: 1- Create your thread: AccessControl() End Sub 4- and finally, add the delegated sub: |
-- 作者:卷积内核 -- 发布时间:10/20/2011 9:10:00 AM -- This error usually shows when Threading operation or Timers are used. UI Controls are naturally belongs to one thread. So if you have another thread to use then use the following simple steps to avoid Cross-Threading
1- Create your thread: 2- Start your thread wherever you want: private void MyThread1() 4- and finally, add the delegated sub: private void PoppingUp() Now from the previous code you will notice that all the codes which wasn't working in the threading sub will be added after "Else" line.
|
W 3 C h i n a ( since 2003 ) 旗 下 站 点 苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》 |
54.688ms |