开发者

Two threads communicating

I have a richTextBoxLog which is public and static.

After I declare it, I start a new thread which initializes new variable named proba. richTextBoxLog should get the value from proba.

The problem is, proba needs time to be initialized, an开发者_开发知识库d I want richTextBoxLog to initialize while proba is initializing.

I want to write something like:

richTextBoxLogFile.richTextBoxLog.Text += proba;

But, when I write it in the method which is called by the previously mentioned thread, I get an exception: "Cross-thread operation not valid: Control 'richTextBoxLog' accessed from a thread other than the thread it was created on."

Can I write something like this: stop the thread, then initialize richTextBoxLog, then start the thread again, then stop it, and the same continues while initializing richTextBoxLog ends.

Edit: I try to use this:

context.Post(new SendOrPostCallback(newMethod), (object)proba);

where context is the context of the main thread and newMethod initializes the value of richTextBoxLog. However, this call is in the method which is started by the new thread, in a while loop:

   while (-1 != (ch = _reader.Read()))
        {
            Console.Write((char)ch);
            proba += ((char)ch).ToString();
            context.Post(new SendOrPostCallback(newMethod), (object)proba);                
        }
        _complete.Set();
    }

The problem I have now is that I want newMethod to be called every time when I enter in the while loop. But, what's happening is: the while loop finishes and after that newMethod is entered about thousand times.


You need to invoke the method with proba:

System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(
     new Action(() => 
         {
               //do stuff with proba
         }
     ));

//edit:

wait, this is a little more complicated. The dispatcher is an object which can simply said execute methods from other threads. This means you need to create a dispatcher in the thread with proba and use that dispatcher in your other thread to execute the method like above.


I'd look into using the BackgroundWorker - it takes a lot of the pain out of operations like this.

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

Otherwise you need to use Control.Invoke to sync up the threads again - http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke.aspx (you shouldn't, and often can't, access the UI from anything other than the UI thread)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜