C#: inner workings: events, Control.BeginInvoke and program exiting = Interruption?

StackOverflow https://stackoverflow.com/questions/9726046

  •  24-05-2021
  •  | 
  •  

سؤال

I'm creating a program with several projects and some projects report back to the main project messages for logging purposes.

Since i am using Asynch sockets, some of these messages come back in different threads, so once they get to the main thread i check InvokeRequired and if true i use this.BeginInvoke to handle the logging.

I need to handle it in the UI thread specially in the case of the server, where i show the last logged messages on a ListBox so i can follow the progress of operations during my tests.

I know sometimes it may happen that a few messages get switched around, but for now i can live with that. For some reason if i use Invoke instead of BeginInvoke, the server will crash if i stop it while clients are connected, and won't even give any exception. But using BeginInvoke i overcame this.

My question regards understanding how events and BeginInvoke work in case of program termination. If an event is on queue or a BeginInvoke has been called just before the program is closed, will it terminate imediatly, cancelling everything? or will it perform all pending actions, in my case log the pending message, and then exit?

هل كانت مفيدة؟

المحلول

You'll have to delay closing the form if you want to ensure all BeginInvoked delegates are executed. You can do so by making it a two-step process, appending another BeginInvoke delegate to the queue that actually closes the form. Like this:

    private bool closing;

    protected override void OnFormClosing(FormClosingEventArgs e) {
        if (!closing) {
            closing = true;
            // Do your stuff
            //...
            this.BeginInvoke(new Action(() => this.Close()));
            e.Cancel = true;
        }
        base.OnFormClosing(e);
    }

نصائح أخرى

When you call BeginInvoke to update UI, the code will be executed by a thread from the threadpool. And if the code raises an exception, it will only terminate the thread, not the whole application. That's why you have seen that your program didn't crash.

When BeginInvoke had just been called, and the program was terminated immediately. The remaining operations (logging ) won't be executed, because the thread from the threadpool

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top