Friday, February 26, 2010

Display a dialog to GUI thread from C#

Delegate.Invoke: Executes synchronously, on the same thread.


Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.

Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.

Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.



Use Code from link http://www.codeproject.com/KB/cs/AvoidingInvokeRequired.aspx

static public class UIHelper


{

static public void UIThread(Control control, MethodInvoker code)

{

if (control.InvokeRequired)

{

control.BeginInvoke(code);

return;

}

control.Invoke();

}

}And then invoke the UIThread like this:



Collapse
Copy Code

UIHelper.UIThread(this, delegate

{

textBoxOut.Text = "New text";

});
 
Or

private delegate void DialogMessage_Delegate(string message);
private bool DialogMessage(string message)
{
if (InvokeRequired)
{
BeginInvoke(new DialogMessage_Delegate(TextMessages), new object[] { message });
}
else
{
if (System.Windows.Forms.MessageBox.Show(message,"Excel Template", MessageBoxButtons.OKCancel)
!= System.Windows.Forms.DialogResult.OK)
return false;
}
return true;
}

No comments:

Post a Comment