I am new to C#, i have read something about threading like begininvoke and eventhandler stuff. but could you explain what’s the following code is doing on the richtextbox?
private void Log(LogMsgType msgtype, string msg)
{
rtfTerminal.Invoke(new EventHandler(delegate
{
rtfTerminal.SelectedText = string.Empty;
rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);
rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
rtfTerminal.AppendText(msg);
rtfTerminal.ScrollToCaret();
}));
}
*is this Invoke similiar to begininvoke?
* in the msdn, it describe it as Executes the specified delegate on the thread that owns the control’s underlying window handle.Not quite sure about the meaning of it.
It executes the code in the anonymous method on the UI thread.
Yes, but
Invokeis synchronous, whereasBeginInvokeis asynchronous. In other words, a call toInvokewill block until the UI thread executes the specified action, whereas BeginInvoke will return immediately, without waiting for the action to be executed by the UI thread.In Windows Forms, controls can only be accessed on the thread that created them. So if you’re executing something on a different thread, and you perform an action on a control from this thread, you can’t do it directly; you need to ask the UI thread to perform this action. That’s what
InvokeandBeginInvokeare for.