Reputation: 1000
The first topic is What wrong with my InvokeRequied
I followed the answer that he recommended it to me but I found a new problem.
The result of below picture is cross thread exception.
What is wrong with my code ?
How to solve this problem ?
Upvotes: 3
Views: 1205
Reputation: 70379
According to MSDN InvokeRequired
can return false
even in cases where InvokeRequired
should be true
- namely in the case that you access InvokeRequired
before the Handle
of that control/form (or a parent of it) has been created.
Basically your check is incomplete which leads to the result you see.
You need to check IsHandleCreated
- if that is false
then you would need to use Invoke
/BeginInvoke
regardless of what InvokeRequired
returns.
[UPDATE]
BUT:
This usually won't work robustly since Invoke
/BeginInvoke
check which thread created Handle
to do their magic...
[/UPDATE]
Only if IsHandleCreated
is true
you act based on what InvokeRequired
returns - something along the lines of:
if (control.IsHandleCreated)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
else
{
// in this case InvokeRequired might lie - you need to make sure that this never happens!
throw new Exception ( "Somehow Handle has not yet been created on the UI thread!" );
}
[UPDATE]
Thus the following is important to avoid this problem
Always make sure that the Handle
is already created BEFORE the first access on a thread other than the UI thread.
According to MSDN you just need to reference control.Handle
in the UI thread to force it being created - in your code this must happen BEFORE the very first time you access that control/form from any thread that is not the UI thread.
[/UPDATE]
Upvotes: 11