jhammer
September 26th, 2006, 11:00 AM
I have a weird problem.
I have a form with a button. When the user press on the button I want to perform a long task. While the task is executed the GUI is disabled, yet it should be alive (no "Not Responding" in the title). When the long task is finished I need to enable the GUI.
Here is the code:
public MyForm:Form
{
(...)
private delegate void VoidDelegate();
private void btn_Click(object sender, EventArgs e)
{
DisableGUI();
VoidDelegate dlg = new VoidDelegate(PerformLongTask);
dlg.BeginInvoke(new AsyncCallback(TaskEnded),null);
}
private void TaskEnded(IAsyncResult ar)
{
EnableGUI(); //Set the Enabled of all the controls to true
}
}
The TaskEnded method throws an exception, because I cannot access the GUI from a different thread. So I figured this solution:
private void TaskEnded(IAsyncResult ar)
{
if (this.InvokeRequired)
{
this.Invoke(new AsyncCallback(TaskEnded), new object() { ar } );
return;
}
EnableGUI(); //Set the Enabled of all the controls to true
}
So if I am from a different thread, I execute the method from the GUI thread using Invoke.
This works most of the times, but in some rare occasions, the Invoke method simply get stuck. Any ideas what the problem is?
I have a form with a button. When the user press on the button I want to perform a long task. While the task is executed the GUI is disabled, yet it should be alive (no "Not Responding" in the title). When the long task is finished I need to enable the GUI.
Here is the code:
public MyForm:Form
{
(...)
private delegate void VoidDelegate();
private void btn_Click(object sender, EventArgs e)
{
DisableGUI();
VoidDelegate dlg = new VoidDelegate(PerformLongTask);
dlg.BeginInvoke(new AsyncCallback(TaskEnded),null);
}
private void TaskEnded(IAsyncResult ar)
{
EnableGUI(); //Set the Enabled of all the controls to true
}
}
The TaskEnded method throws an exception, because I cannot access the GUI from a different thread. So I figured this solution:
private void TaskEnded(IAsyncResult ar)
{
if (this.InvokeRequired)
{
this.Invoke(new AsyncCallback(TaskEnded), new object() { ar } );
return;
}
EnableGUI(); //Set the Enabled of all the controls to true
}
So if I am from a different thread, I execute the method from the GUI thread using Invoke.
This works most of the times, but in some rare occasions, the Invoke method simply get stuck. Any ideas what the problem is?