Roll your own message loop, any pitfalls?

This question is slightly related to this exception handling question . The workaround I found there is to flip my own message loop.

So, my main method now looks basically like this:

[STAThread]
static void Main() {
  // this is needed so there'll actually an exception be thrown by
  // Application.Run/Application.DoEvents, instead of the ThreadException
  // event being raised.
  Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);

  Form form = new MainForm();
  form.Show();

  // the loop is here to keep app running if non-fatal exception is caught.
  do {
    try {
      Application.DoEvents();
      Thread.Sleep(100);
    }
    catch (Exception ex) {
      ExceptionHandler.ConsumeException(ex);
    }
  }
  while (!form.IsDisposed);
}

What interests me is a safe / decent way to replace the more typical 'Application.Run (new MainForm ()); whether it is used to handle exceptions or for anything else, or should I always stick with Application.Run?

, (splashscreen), , , - (: -))

+2
3

Pitfall 1:

Thread.Sleep(100);

. WaitMessage().

, .

Application.Run() (, .Net Reflector).

+2

, IMessageFilter, Application.AddMessageFilter, .

+2

Yes ... I think some components will not work with this code. Some of them need to live in a thread in which there is an application. Run it to efficiently pick up your messages.

0
source

Source: https://habr.com/ru/post/1696852/


All Articles