-1

I tried to wrote this code to update the text of a textBox while backgroundworker is working.

#region variables

        public delegate void updateTextBoxDelegate(string s, bool directory);
        updateTextBoxDelegate delegateTextBox;

#endregion

#region somewhereInsideForm1Constructor

        delegateTextBox = new updateTextBoxDelegate(updateTextBox);

#endregion

#region methods

        public void updateTextBox(string s, bool directory)
        {
            if (directory)
            {
                textBox1.Text += s + System.Environment.NewLine;
            }
            else
            {
                textBox1.Text += "   --> " + s + System.Environment.NewLine;
            }
        }

#endregion


#region somewhereInsideBackGroundWorker_doWork

       delegateTextBox(path.FullName, true);

#endregion

and in this situation occurs an Exception of Cross Threading:

here:

      textBox1.Text += s + System.Environment.NewLine;

and here:

      delegateTextBox(path.FullName, true);

What's the error???

Thanks!

Gasta87
  • 225
  • 5
  • 16
  • Don't create custom delegates. Use `System.Action` instead. – Federico Berasategui May 28 '13 at 20:10
  • I'm not totally sure what your question is, but for some reason I get the feeling the answer is here: http://stackoverflow.com/questions/906057/problem-with-delegate-syntax-in-c-sharp?rq=1. Also this should help explain Cross Threading and the UI http://msdn.microsoft.com/en-us/library/ms171728.aspx – deepee1 May 28 '13 at 20:10
  • 4
    You've already answered your question: You have a delegate that changes a TextBox when invoked; you invoke the delegate from a BackgroundWorker, i.e., from a thread other than the GUI thread; this causes an Exception of Cross Threading. Solution: http://stackoverflow.com/questions/661561 – dtb May 28 '13 at 20:10
  • I was told that delegates are used specially to manage the cross thread exceptions... isn't it? – Gasta87 May 28 '13 at 20:14
  • 1
    Defining a delegate doesn't automatically make your UI updates thread safe. What you need to do is DELEGATE the responsibility to updating the UI to the UI thread using a method such as Control.BeginInvoke. Check out the 2 links I provided above that show examples on doing what you are looking for. – deepee1 May 28 '13 at 20:31

1 Answers1

0

If I get you well, back ground thread can not operate the UI controls directly. If you are using WPF, you can try to use Dispatcher. Instead of creating your own thread do something like this for the background work

Object[] args = {path.FullName, true };
this.Dispatcher.BeginInvoke(delegateTextBox, args);

Hope this will help.

Jiji TANG
  • 91
  • 3