C# threading question: Invoke() fails with ObjectDisposedException
-
Your code should read:
if (this.InvokeRequired) { ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue); this.Invoke(pvd, new object\[\] { value }); return; } else { m\_progressBar.Value = value; }
I usually check to see if ISyncronizeInvoke is implemented and work on interface. This is how it would look:
ISyncronizeInvoke sync = (ISyncronizeInvoke)this; if (sync != null) { if(sync.InvokeRequired) { ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue); object\[\] args = { value }; sync.Invoke(pvd, args); return; } else { m\_progressBar.Value = value; } }
Tried both and they fail. It always fails at the Invoke() call.
-
Tried both and they fail. It always fails at the Invoke() call.
-
No, the value for the sync object is valid. It goes into the loop and when it hits invoke, it barfs. You can see the callstack in one of the previous posts. Thanks, Keith
-
Hello, I have been struggling with some threading issues over the last couple of days. I am getting close to getting this thing to work but there are still a few niggles. So, I have a thread that is called as follows and after the thread starts, my application shows a modal dialog box. So far so good:
t = new System.Threading.Thread
(delegate()
{
result = Init();
});
t.Start();
dialog.ShowDialog();This works fine and there are no problems. Now, the user can hide this dialog box and when that happens the subsequent code gets executed as expected and this is not a problem. Also, I use ShowDialog(), so hiding or calling Close() should not call dispose as indicated in the docs. Also, the dialog box is a singleton and lives for the duration of the application. Now, my dialog box has a progress bar which gets updated by the calling thread and the update method that gets executed is as follows:
delegate void ProgressValueDelegate(int value);
public void SetProgressValue(int value)
{
if (this.InvokeRequired)
{
ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue);
this.Invoke(pvd, new object[] { value });
}
else
{
m_progressBar.Value = value;
}
}So, as soon as the dialog box is hidden, the subsequent call crashes at the Invoke() call. I think there is some race condition going on somewhere because in the debugger the InvoleRequired value is fasle. However, the code has already entered the 'if' condition. Does anyone know how I can handle this sort of situation? Thanks, Keith
Have you done an experiment where the dialog is hidden before you even start the thread? This would avoid the possible race condition, and would demonstrate if the problem is indeed a race condition, or something else (the latter being true if you still get an exception in the invoke)? You could probably use the debugger (with a breakpoint in both threads, and stepping the dialog closed before stepping the background thread into SetProgressValue()) to force your way past the possible race condition.
-
Hello, I have been struggling with some threading issues over the last couple of days. I am getting close to getting this thing to work but there are still a few niggles. So, I have a thread that is called as follows and after the thread starts, my application shows a modal dialog box. So far so good:
t = new System.Threading.Thread
(delegate()
{
result = Init();
});
t.Start();
dialog.ShowDialog();This works fine and there are no problems. Now, the user can hide this dialog box and when that happens the subsequent code gets executed as expected and this is not a problem. Also, I use ShowDialog(), so hiding or calling Close() should not call dispose as indicated in the docs. Also, the dialog box is a singleton and lives for the duration of the application. Now, my dialog box has a progress bar which gets updated by the calling thread and the update method that gets executed is as follows:
delegate void ProgressValueDelegate(int value);
public void SetProgressValue(int value)
{
if (this.InvokeRequired)
{
ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue);
this.Invoke(pvd, new object[] { value });
}
else
{
m_progressBar.Value = value;
}
}So, as soon as the dialog box is hidden, the subsequent call crashes at the Invoke() call. I think there is some race condition going on somewhere because in the debugger the InvoleRequired value is fasle. However, the code has already entered the 'if' condition. Does anyone know how I can handle this sort of situation? Thanks, Keith
I have had a similar problem many times. In a lot of my apps, I have a textbox that sits on a form, and any thread can write a line to it. I have poured over documentation, and never found a solution to whether the form has been closed or not. So, I simply added the following :
private volatile bool formClosed = false;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
formClosed = true;
}delegate void ProgressValueDelegate(int value);
public void SetProgressValue(int value)
{
if (this.InvokeRequired)
{
ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue);
this.Invoke(pvd, new object[] { value });
}
else
{
if( formClosed == false )
{
m_progressBar.Value = value;
}
}
}BTW, you can also move the if to before the
if (this.InvokeRequired)
to save yourself an Invoke call if it won't be doing anything in anycase. -
I have had a similar problem many times. In a lot of my apps, I have a textbox that sits on a form, and any thread can write a line to it. I have poured over documentation, and never found a solution to whether the form has been closed or not. So, I simply added the following :
private volatile bool formClosed = false;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
formClosed = true;
}delegate void ProgressValueDelegate(int value);
public void SetProgressValue(int value)
{
if (this.InvokeRequired)
{
ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue);
this.Invoke(pvd, new object[] { value });
}
else
{
if( formClosed == false )
{
m_progressBar.Value = value;
}
}
}BTW, you can also move the if to before the
if (this.InvokeRequired)
to save yourself an Invoke call if it won't be doing anything in anycase.HuntrCkr wrote:
you can also move the if
Not a good idea. Invoke puts the job in the input queue of the main thread; a "close this form" command could already be awaiting execution. You need to perform the test as late as possible. :)
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.
-
HuntrCkr wrote:
you can also move the if
Not a good idea. Invoke puts the job in the input queue of the main thread; a "close this form" command could already be awaiting execution. You need to perform the test as late as possible. :)
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.
In fact, it doesn't make a difference. Common misunderstanding. Let me first put in the code snippet
public void SetProgressValue(int value)
{
if( formClosed == true )
{
return;
}if (this.InvokeRequired) { ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue); this.Invoke(pvd, new object\[\] { value }); } else { m\_progressBar.Value = value; }
}
When
SetProgressValue
is called from another thread, the first thing that happens is the check if the form is closed already. Let's take you hypothetical situation where a FormClosing event is queued, but has not been executed yet.formClosed
isfalse
, so nowthis.InvokeRequired
is checked. It'strue
so a call toSetProgressValue
is queued as well. The FormClosing event fires, andformClosed
is set to true. Next, the queued call toSetProgressValue
occurs. First thing, we checkformClosed
which is nowtrue
, so the function is terminated immediately. The common misconception is that Invoke simply transfers the call to the correct thread, but in fact the function is called all over again. Another thing many people are not aware of is that the call toInvoke
actually halts the thread until the Invoked delegate has been executed in the GUI thread, which can cause major slowdowns. Rather useBeginInvoke
. It does the same thing in this scenario, but does not block the calling thread. -
Hello, I have been struggling with some threading issues over the last couple of days. I am getting close to getting this thing to work but there are still a few niggles. So, I have a thread that is called as follows and after the thread starts, my application shows a modal dialog box. So far so good:
t = new System.Threading.Thread
(delegate()
{
result = Init();
});
t.Start();
dialog.ShowDialog();This works fine and there are no problems. Now, the user can hide this dialog box and when that happens the subsequent code gets executed as expected and this is not a problem. Also, I use ShowDialog(), so hiding or calling Close() should not call dispose as indicated in the docs. Also, the dialog box is a singleton and lives for the duration of the application. Now, my dialog box has a progress bar which gets updated by the calling thread and the update method that gets executed is as follows:
delegate void ProgressValueDelegate(int value);
public void SetProgressValue(int value)
{
if (this.InvokeRequired)
{
ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue);
this.Invoke(pvd, new object[] { value });
}
else
{
m_progressBar.Value = value;
}
}So, as soon as the dialog box is hidden, the subsequent call crashes at the Invoke() call. I think there is some race condition going on somewhere because in the debugger the InvoleRequired value is fasle. However, the code has already entered the 'if' condition. Does anyone know how I can handle this sort of situation? Thanks, Keith
It seems that, for some reason, your dialog is beeing disposed (and with it, all it's controls). It's really difficult to know why without more code. But have you tried handling FormClosing event? There you could do this: e.Cancel = true; this.Hide(); Maybe that will work out for you, hiding instead of closing. Let me know if it solves your problem Regards, Fábio
-
In fact, it doesn't make a difference. Common misunderstanding. Let me first put in the code snippet
public void SetProgressValue(int value)
{
if( formClosed == true )
{
return;
}if (this.InvokeRequired) { ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue); this.Invoke(pvd, new object\[\] { value }); } else { m\_progressBar.Value = value; }
}
When
SetProgressValue
is called from another thread, the first thing that happens is the check if the form is closed already. Let's take you hypothetical situation where a FormClosing event is queued, but has not been executed yet.formClosed
isfalse
, so nowthis.InvokeRequired
is checked. It'strue
so a call toSetProgressValue
is queued as well. The FormClosing event fires, andformClosed
is set to true. Next, the queued call toSetProgressValue
occurs. First thing, we checkformClosed
which is nowtrue
, so the function is terminated immediately. The common misconception is that Invoke simply transfers the call to the correct thread, but in fact the function is called all over again. Another thing many people are not aware of is that the call toInvoke
actually halts the thread until the Invoked delegate has been executed in the GUI thread, which can cause major slowdowns. Rather useBeginInvoke
. It does the same thing in this scenario, but does not block the calling thread.My mistake. You're right about the test, if it sits on the top of the method, it gets executed twice so it can't go wrong. However executing it twice all the time may be a high price to pay for potentially saving one thread switch when the form closes. I do not really agree on the BeginInvoke issue. While technically correct, I don't like the SetProgressValue method to behave synchronously when called on the main thread and asynchronously when called anywhere else. If there is a potential asynchronous operation, it should be reflected in the method name (BeginSetProgressValue?) and it'd better be consistent (as in: don't test InvokeRequired, just call BeginInvoke). Furthermore, having a mix of such Invoke and BeginInvoke patterns (several Controls each using their own little SetProgressValue method) could result in incomprehensible app behavior. :)
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.
-
My mistake. You're right about the test, if it sits on the top of the method, it gets executed twice so it can't go wrong. However executing it twice all the time may be a high price to pay for potentially saving one thread switch when the form closes. I do not really agree on the BeginInvoke issue. While technically correct, I don't like the SetProgressValue method to behave synchronously when called on the main thread and asynchronously when called anywhere else. If there is a potential asynchronous operation, it should be reflected in the method name (BeginSetProgressValue?) and it'd better be consistent (as in: don't test InvokeRequired, just call BeginInvoke). Furthermore, having a mix of such Invoke and BeginInvoke patterns (several Controls each using their own little SetProgressValue method) could result in incomprehensible app behavior. :)
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.
Luc Pattyn wrote:
My mistake. You're right about the test, if it sits on the top of the method, it gets executed twice so it can't go wrong. However executing it twice all the time may be a high price to pay for potentially saving one thread switch when the form closes.
Hey, no problem. I make mistakes all the time. Hence my motto There are two ways to write bug free software. Only the third method works though ;P As for the performance cost argument, I think it's highly dependent on the scenario.
Luc Pattyn wrote:
I do not really agree on the BeginInvoke issue.
I agree with you. In a large project or any other production level code, things should be done consistently, and all the things you mention are true. That is why I stated that in this simplified scenario, BeginInvoke doesn't really matter. If the function was even remotely more complex, or had more than 3 lines to execute with the synchronous vs. asynchronous path, it would be far more important. Glad we could agree :)
-
My mistake. You're right about the test, if it sits on the top of the method, it gets executed twice so it can't go wrong. However executing it twice all the time may be a high price to pay for potentially saving one thread switch when the form closes. I do not really agree on the BeginInvoke issue. While technically correct, I don't like the SetProgressValue method to behave synchronously when called on the main thread and asynchronously when called anywhere else. If there is a potential asynchronous operation, it should be reflected in the method name (BeginSetProgressValue?) and it'd better be consistent (as in: don't test InvokeRequired, just call BeginInvoke). Furthermore, having a mix of such Invoke and BeginInvoke patterns (several Controls each using their own little SetProgressValue method) could result in incomprehensible app behavior. :)
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.
I'm not sure how to satisfy Luc's issue over mixing sync and async behaviours, but how about this variation:
public void SetProgressValue(int value)
{
MethodInvoker method = delegate
{
if (!formClosed)
{
m_progressBar.Value = value;
}
};if (InvokeRequired) BeginInvoke(method); else method.Invoke();
}
First, you don't need to worry about keeping the delegate's parameters aligned with the method's parameters (makes maintenance easier). Second, you shouldn't test boolean values against true/false (just take their value). Third, it uses the async BeginInvoke when not on the GUI thread.
-
Hello, I have been struggling with some threading issues over the last couple of days. I am getting close to getting this thing to work but there are still a few niggles. So, I have a thread that is called as follows and after the thread starts, my application shows a modal dialog box. So far so good:
t = new System.Threading.Thread
(delegate()
{
result = Init();
});
t.Start();
dialog.ShowDialog();This works fine and there are no problems. Now, the user can hide this dialog box and when that happens the subsequent code gets executed as expected and this is not a problem. Also, I use ShowDialog(), so hiding or calling Close() should not call dispose as indicated in the docs. Also, the dialog box is a singleton and lives for the duration of the application. Now, my dialog box has a progress bar which gets updated by the calling thread and the update method that gets executed is as follows:
delegate void ProgressValueDelegate(int value);
public void SetProgressValue(int value)
{
if (this.InvokeRequired)
{
ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue);
this.Invoke(pvd, new object[] { value });
}
else
{
m_progressBar.Value = value;
}
}So, as soon as the dialog box is hidden, the subsequent call crashes at the Invoke() call. I think there is some race condition going on somewhere because in the debugger the InvoleRequired value is fasle. However, the code has already entered the 'if' condition. Does anyone know how I can handle this sort of situation? Thanks, Keith
-
Thanks for your reply. I did check all that and the
IsDisposed
property is false. Here is the call stackObject name: ProgressForm'.
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at ProgressForm.SetProgressDescription(String description)
at Mycomponent.UpdateProgressDialogDescription(String description)
at Mycomponent.Initialize(Int32 hashCode, Int32 numSeries, Int32[] nInstances)
at
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()</ExceptionString></Exception></TraceRecord>
An unhandled exception of type 'System.ObjectDisposedException' occurred in System.Windows.Forms.dllCheers,
Keith -
I'm not sure how to satisfy Luc's issue over mixing sync and async behaviours, but how about this variation:
public void SetProgressValue(int value)
{
MethodInvoker method = delegate
{
if (!formClosed)
{
m_progressBar.Value = value;
}
};if (InvokeRequired) BeginInvoke(method); else method.Invoke();
}
First, you don't need to worry about keeping the delegate's parameters aligned with the method's parameters (makes maintenance easier). Second, you shouldn't test boolean values against true/false (just take their value). Third, it uses the async BeginInvoke when not on the GUI thread.
I like it, especially if you scrap the "Begin" of BeginInvoke. :)
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.
-
Hello, I have been struggling with some threading issues over the last couple of days. I am getting close to getting this thing to work but there are still a few niggles. So, I have a thread that is called as follows and after the thread starts, my application shows a modal dialog box. So far so good:
t = new System.Threading.Thread
(delegate()
{
result = Init();
});
t.Start();
dialog.ShowDialog();This works fine and there are no problems. Now, the user can hide this dialog box and when that happens the subsequent code gets executed as expected and this is not a problem. Also, I use ShowDialog(), so hiding or calling Close() should not call dispose as indicated in the docs. Also, the dialog box is a singleton and lives for the duration of the application. Now, my dialog box has a progress bar which gets updated by the calling thread and the update method that gets executed is as follows:
delegate void ProgressValueDelegate(int value);
public void SetProgressValue(int value)
{
if (this.InvokeRequired)
{
ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue);
this.Invoke(pvd, new object[] { value });
}
else
{
m_progressBar.Value = value;
}
}So, as soon as the dialog box is hidden, the subsequent call crashes at the Invoke() call. I think there is some race condition going on somewhere because in the debugger the InvoleRequired value is fasle. However, the code has already entered the 'if' condition. Does anyone know how I can handle this sort of situation? Thanks, Keith
-
Hello, I have been struggling with some threading issues over the last couple of days. I am getting close to getting this thing to work but there are still a few niggles. So, I have a thread that is called as follows and after the thread starts, my application shows a modal dialog box. So far so good:
t = new System.Threading.Thread
(delegate()
{
result = Init();
});
t.Start();
dialog.ShowDialog();This works fine and there are no problems. Now, the user can hide this dialog box and when that happens the subsequent code gets executed as expected and this is not a problem. Also, I use ShowDialog(), so hiding or calling Close() should not call dispose as indicated in the docs. Also, the dialog box is a singleton and lives for the duration of the application. Now, my dialog box has a progress bar which gets updated by the calling thread and the update method that gets executed is as follows:
delegate void ProgressValueDelegate(int value);
public void SetProgressValue(int value)
{
if (this.InvokeRequired)
{
ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue);
this.Invoke(pvd, new object[] { value });
}
else
{
m_progressBar.Value = value;
}
}So, as soon as the dialog box is hidden, the subsequent call crashes at the Invoke() call. I think there is some race condition going on somewhere because in the debugger the InvoleRequired value is fasle. However, the code has already entered the 'if' condition. Does anyone know how I can handle this sort of situation? Thanks, Keith
How are you hiding the dialog box? After some googling, it appears you aren't the only one facing this problem. Most helpful responses seem to suggest using try / catch and ignoring ObjectDisposedExceptions. This might work, because if the problem happens when the dialog is hidden, the user won't expect the progress bar to increment, because it's not visible... http://www.devnewsgroups.net/windowsforms/t38313-parkingwindow-objectdisposedexception-system-windows-forms.aspx[^] http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2006-08/msg01372.html[^]
-
Hello, I have been struggling with some threading issues over the last couple of days. I am getting close to getting this thing to work but there are still a few niggles. So, I have a thread that is called as follows and after the thread starts, my application shows a modal dialog box. So far so good:
t = new System.Threading.Thread
(delegate()
{
result = Init();
});
t.Start();
dialog.ShowDialog();This works fine and there are no problems. Now, the user can hide this dialog box and when that happens the subsequent code gets executed as expected and this is not a problem. Also, I use ShowDialog(), so hiding or calling Close() should not call dispose as indicated in the docs. Also, the dialog box is a singleton and lives for the duration of the application. Now, my dialog box has a progress bar which gets updated by the calling thread and the update method that gets executed is as follows:
delegate void ProgressValueDelegate(int value);
public void SetProgressValue(int value)
{
if (this.InvokeRequired)
{
ProgressValueDelegate pvd = new ProgressValueDelegate(SetProgressValue);
this.Invoke(pvd, new object[] { value });
}
else
{
m_progressBar.Value = value;
}
}So, as soon as the dialog box is hidden, the subsequent call crashes at the Invoke() call. I think there is some race condition going on somewhere because in the debugger the InvoleRequired value is fasle. However, the code has already entered the 'if' condition. Does anyone know how I can handle this sort of situation? Thanks, Keith
When developing apps that use worker threads which like to report back a status, a good technique I have used on projects is to set up a data structure (class or struct) that holds member variables for all the "stats" that the threads must update. Each thread updates the fields in the class/struct, without caring who may be "listening". For dialogs that like to report the status of these threads (i.e. using progress bars, updating text boxes etc), they query the class / struct member variables. This way the relationship is decoupled and state-free. This is a technique we used a lot in the Win32 programming model, and it works just as well in .Net.