0

I've inherited a legacy WinForms app that is full of horrible threading issues and cross-thread form updates. The developer has made use of Control.BeginInvoke to marshal the calls but has not been very successful with it. I think the original developer was a C programmer so their approach is very linear and imperative. I sympathize because I made a lot of the same mistakes 20+ years ago when C# first appeared.

I'm wondering if I replace these cross-thread control updates with MediatR notifications, would this marshal the handlers to the UI's STA thread, or will I still have to be concerned with thread marshaling?

I've solved this type of problem on other occasions using the Reactive Extensions, but I wonder whether MediatR would help in a more straightforward way inthis instance?

Tim Long
  • 13,508
  • 19
  • 79
  • 147

1 Answers1

0

MediatR does not know anything about WinForms (or SynchronizationContexts in general). It's "just" a simple pattern to decouple commands/events and their handlers.

If you're using this in an app where synchronization is important (winforms/wpf), you will have to do the dispatching yourself. E.g. for winforms: use InvokeRequired/Invoke pattern to post things to the UI thread.

Remco Ros
  • 1,467
  • 15
  • 31
  • A better suggestion is to make use of `IProgress` delegates to update the UI. `InvokeRequired/Invoke` (ancient / littered with problems) has already been used, the OP mentioned `BeginInvoke()` calls to marshal to the UI Thread – Jimi Aug 01 '23 at 15:43
  • Excellent answer, thank you. – Tim Long Aug 02 '23 at 06:57