Saturday, December 4, 2010

Cross Thread Exception







    In multi threaded application when you start you application and create one thread to preform some action in background and when you set some controls property over that thread you may be getting "Cross-Thread exception". In this case you can not set property of the control from the thread other then where it initialized.so you can set the property with the use of reflection as below.






private sub SetControlPrpertyValue(byval oControl as control, byval propcName as string,byval propValue as string) 

 If oControl.InvokeRequired Then 

oControl.Invoke(d,
Dim d As New SetControlValueCallback(AddressOf SetControlPrpertyValue)New Object() {oControl, propName, propValue}) 

Else
Dim t As Type = oControl.[GetType]() 
Dim props As PropertyInfo() = t.GetProperties()

 For Each p As PropertyInfo In props 
    If p.Name.ToUpper() = propName.ToUpper()  Then 
         p.SetValue(oControl, propValue, Nothing)
       
    End If
 Next
end
End if
End Sub

No comments:

Post a Comment