0

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.

Jan J.
  • 45
  • 5
  • Try `var result = ParentForm.Invoke(() => _controller.SendInvoice(ParentForm));`. The MethodInvoker delegate does not support return values. – Klaus Gütter Nov 21 '22 at 09:14
  • Does this answer your question? [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) –  Nov 21 '22 at 09:17

2 Answers2

1

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); 
BWA
  • 5,672
  • 7
  • 34
  • 45
0

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)));
shingo
  • 18,436
  • 5
  • 23
  • 42
  • Unfortunately, I have "specific" controller class, where Invoke is protected and it HAVE to stay like this. Thanks though – Jan J. Nov 21 '22 at 09:59