Home > Back-end >  Passing a control from another thread as a method parameter on other thread
Passing a control from another thread as a method parameter on other thread

Time:11-21

I have async operation, in which I call a non-void method:

var result = _controller.SendInvoice(this.ParentForm);

I was getting error "Cross-thread operation not valid: Control 'ParentForm' accessed from a thread other than the thread it was created on"

I've managed to fix it by writing code like this:

ParentForm.Invoke(new MethodInvoker(delegate { _controller.SendInvoice(ParentForm); }));

The problem is that I have to get the return result of the method SendInvoice, but the "solution" above does not solving it for me because it doesn't return value from SendInvoice() method.

CodePudding user response:

You probably want to send only data not all form. Create type Invoice and copy data from form to it, and send it to your method.

Invoice invoice;
//Here copy data
_controller.SendInvoice(invoice); 

CodePudding user response:

The problem is in .Net Framework, you cannot access ParentForm from a non-UI thread (exactly the thread the form is created), but you can call Invoke on the control. This method is also able to return a value.

var result = (RETURN-TYPE)_controller.Invoke(
    new Func<RETURN-TYPE>(() => _controller.SendInvoice(ParentForm)));
  • Related