开发者

Calling a method from a backgroundworker

I have a backgroundworker which calls a method in the DoWork event.

this method accesses a dataset in the UI Thread and it also calls a another method in the UI Thread.

my problem comes in when the method requires access to datasets and methods that exists in the Ui Thread, I get a cross thread operation not valid error.

How can I access Items UI Thread? Is it possible for me to access it using the backgroundworker or must I use another method of running my method in a backg开发者_开发技巧round thread

Thanks


You just need to marshal the method call to the UI thread.
On WinForms:

void DoWork(...)
{
    YourMethod();
}

void YourMethod()
{
    if(yourControl.InvokeRequired)
        yourControl.Invoke((Action)(() => YourMethod()));
    else
    {
        //Access controls
    }
}


you should use the Dispatcher.Invoke method

for more info have a look at the below link

http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.invoke.aspx


A control created in the UI thread cannot be accessed in another thread in normal fashion. Please create a delegate and invoke the delegate using control.Invoke.

The method sample provided below can be used to enable visibility on a button regardless of the thread context you are in.

private void EnableButtonVisibility( Button btn, bool enable)    
{     
    if ( !btn.InvokeRequired )    
    {    
        btn.Visible = enable;    
    }   
    else    
    {    
        btn.Invoke( new EnableButtonVisibilityHandler( EnableButtonVisibility ), btn, enable );    
    }    
}    
 delegate void EnableButtonVisibilityHandler( Button btn, bool enable);

You can also achieve the same using Action<Button, bool>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜