0

This is the error I am receiving. I have a button on a winforms control (as depicted below). I have an async void method that is attached to the click event handler (as depicted below) Error Button on second tab

The issue that I am having is that this code runs perfectly fine when I first load in this form, I can click the button 1,000+ times and there is no cross threading errors that occur.

The ONLY time that I get this error is when I do the following

  1. hide the form form.Hide() (with keeping a reference to the form)
  2. show the form for a second time form.ShowDialog()
  3. click the refresh button

It seems like all of the buttons on the form will then have some sort of cross-threading issue when calling into UI controls from async method calls. It is almost as if hiding and then re-showing the dialog does something to make new controls on a new thread BUT it never calls the Initialize method again.

Does anyone know why I am having an issue?

EDIT This is also a VSTO excel addin project. The form is getting created by a ribbon button click and I hold on to a reference of the form in the ribbon class to re-show it

  • 1
    Can you please provide a [mcve] with all of the steps to replicate this issue? – Enigmativity Oct 21 '21 at 02:34
  • How's that [mcve] coming along? – Enigmativity Oct 21 '21 at 03:43
  • 1
    I began working on it but couldn't replicate the exact issue I was having. I'll try to work on it some more tomorrow but it is late here. It may be a day or so before I'm able to put that together – Jeremy Buentello Oct 21 '21 at 04:06
  • I would suggest. 1. Check what thread the event is raised on (should be UI/Main thread). 2. What thread is used after the await (it should be the same). 3. That there is only one UI thread. I would expect that multiple UI threads could give the problem you are describing. – JonasH Oct 21 '21 at 06:50
  • Try to understand which thread you are using when you create the form at the beginning and when you show the form later. Use `Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);` They should be the same. Moreover do you have this problem only on `async` methods with `await`? – GibbOne Oct 21 '21 at 08:14
  • @GibbOne - This is why a [mcve] would be awesome. – Enigmativity Oct 21 '21 at 08:58
  • @Enigmativity sure! – GibbOne Oct 21 '21 at 09:27
  • 1
    Check the SynchronizatinContext.Current in your Form.OnShown method. I've already seen that it get's lost under VSTO and is not a WindowsFormsSynchronizationContext anymore, thus not doing proper continuation on the main thread by using async/await. It is probably not a good idea to keep a reference to a hidden form in VSTO, why do you need that? – Steeeve Oct 22 '21 at 20:10

0 Answers0