Hye everybody!
I've got a problem with a textbox access. I'm using VS2008, WPF, c#.
I've got two projects in a solution. In one project i update an xml doc. In the other project, in wich my textbox is declared, i have declared a FileSystemWatcher who detect when my xml doc change. When it changes i whant to put a text in my textbox. Unfortunatly it raise a InvalidOperationExeption and write: "The calling thread cannot access this object because a different thread owns it.". I don't know how to solve this problem. Is anyone can help?
Loading
yohannPosted Aug 4, 2008, 4:03 AM
again, thanks.
Ryan AlfordPosted Aug 1, 2008, 3:21 PM
namespace ThreadingUIUpdate
{
public partial class Form1 : Form
{
public delegate void UpdateTextCallback(string message);
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(TestThread));
thread.Start();
}
private void UpdateText(string message)
{
textBox1.Text = message;
}
private void TestThread()
{
for (int i = 0; i <= 1000000000; i++)
{
Thread.Sleep(1000);
textBox1.Invoke(new UpdateTextCallback(this.UpdateText), new object[] { i.ToString() });
}
}
}
}
This is what you need to do. You are trying to do a cross-thread action, which isn't allowed. The "Invoke" method will fire the delegate on the thread that owns the control.
Nilanka DharmadasaPosted Aug 1, 2008, 6:51 AM
Yohann,
The 'TextBoxHandler' code should be there inside the class where the text box is created. Did you try that way?
yohannPosted Aug 1, 2008, 5:47 AM
I tried your solution of delegate but it seems to doesn't work. The same problem raises ("The calling thread cannot access this object because a different thread owns it."). I don't know wich thread can own the textbox! ...
yohannPosted Aug 1, 2008, 5:10 AM
the probleme is that i can't acces my textbox via the textboxhandler class. All the controls in my window application aren't public. So How can I access them from the outside?
Nilanka DharmadasaPosted Aug 1, 2008, 4:40 AM
According to what i understood, the text box is owned by one thread while the file system watcher is runing on another thread. You may use a delegate to solve this issue.
public
partial class TextBoxHandler{
public delegate void DelegateUpdateText(String s);public DelegateUpdateText _DelegateUpdateText ;
public
TextBoxHandler(){
_DelegateUpdateText = new DelegateUpdateText(this.UpdateTextMethod);
}
public void UpdateTextMethod(string s){
TextBox1.Text = s;
}
}
Now in the file system watcher you can call this delegate '_DelegateUpdateText'. Not the method 'UpdateTextMethod'.
TextBoxHandler _obj = new TextBoxHandler ();
_obj .Invoke(_obj ._DelegateUpdateText,
new object[] { "File change detected." });I'm not sure that I have identified your problem exactly. Hope this one will work.