Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello!

I use the following method to invoke something:

C#
public void InvokeHelper(object from, object to)
        {
            BeginInvoke(new MethodInvoker(delegate()
            {
                from = to;
            }));
        }


But sometimes it throws an invalidcrossthreadcall exception. I use it about 50 times a second.

So the question is why is it throw exception?
Posted
Comments
#realJSOP 14-Jan-11 10:29am    
What happens if you call it less frequently?
velvet7 14-Jan-11 10:33am    
Well, maybe if i call it less frequently solves the problem, but I have to call it 50 times a seco
#realJSOP 14-Jan-11 10:39am    
Were the from and to objects created on the UI thread, or in the thread that's calling the InvokeHelper method?
Nish Nishant 14-Jan-11 10:51am    
Post more info such as whether this is Silverlight, Winforms, WPF etc.
Sergey Alexandrovich Kryukov 14-Jan-11 10:58am    
@velvet7: of course not, this is a bug! Normally, Invoke always work, but this is not real Invoke.
Please 1) show the code of MethodInvoker; 2) Is it WinForms? 3) If your code, BeginInvoke if the method of what instance of what class (in other words, in what class you write this InvokeHelper method?

The problem is way too easy to resolve if you answer these questions.

Try writing it like this:
public void InvokeHelper(object from, object to)
{
 BeginInvoke( (MethodInvoker) delegate { from = to; });
}


Regards
Espen Harlinn
 
Share this answer
 
I would suggest to first check if it is necessary. You might also need to check IsHandleCreated to ensure that the control is created. Have a look at the first link for more info on that and for an example check the second link.

if(this.InvokeRequired)
{
  this.BeginInvoke(method);
} else
{
  method();
}


http://msdn.microsoft.com/nl-nl/library/system.windows.forms.control.invokerequired.aspx[^]

http://msdn.microsoft.com/nl-nl/library/ms171728.aspx[^]

Good luck!
 
Share this answer
 
Comments
Nish Nishant 14-Jan-11 12:08pm    
Proposed as answer, voted 5.
you might want to consider the context as well


C#
public void InvokeHelper(object from, object to, System.Threading.SynchronizationContext context)
        {

              _conex.Post(new SendOrPostCallback((obj) => {
                                                     
                     //your code here
                     }
              ), null);

        }
 
Share this answer
 
Consider to use ThreadSynchronization pattern.
As a remember BeginInvoke returns asyncResult
So, you can use AsyncWaitHandle.WaitOne
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900