Monday, August 19, 2013

Pass By Reference not allowed in UI threading

The code below does not allow pass by reference to be used in UI threading
particularly method Invoker.
Code:
  private void ShowPassMeta(ref int passedSound)  
  {  
       if (lblPassSoundex.InvokeRequired)  
       {  
            lblPassSoundex.Invoke((MethodInvoker)delegate  
            {  
                 ShowPass(ref passedSound);  
            });  
       }  
       else  
       {  
            lblPassSoundex.Text = (++passedSound).ToString();  
       }        
  }

The solution is to store the method parameter in another variable as shown below:
Code:
  private void ShowPassMeta(ref int passedSound)  
  {        
    var passedSound1 = passedSound;  
    if (lblPassSoundex.InvokeRequired)  
    {  
      lblPassSoundex.Invoke((MethodInvoker)delegate  
      {  
        ShowPassMeta(ref passedSound1);  
      });  
    }  
    else  
    {  
      lblPassSoundex.Text = (++passedSound1).ToString();  
       }  
  }
Cheers!

0 comments:

Post a Comment