public delegate void SetTextDelegate(string text);
public void SetText(string text)
{
myTextBox.Text = text;
}
public void SetTextFromAnywhere(string text)
{
if (myTextBox.InvokeRequired)
{
myTextBox.Invoke(new SetTextDelegate(SetText), text);
}
else
{
SetText(text);
}
}
Keep in mind that the thread that calls Invoke will wait for the delegate to return. This can be the cause of some insidious deadlock and threadpool starving problems. A more robust multi-threading pattern is to use BeginInvoke, which schedules the delegate to executed, rather than executing it immediately. For you old C programmers, it's the difference between SendMessage and PostMessage. Also note that Invoke returns an object, which is whatever the delegate returns. With BeginInvoke you can use a delegate with a return value, but you must call EndInvoke to retrieve it.
No comments:
Post a Comment