In C#, wait on the mainthread while continuing to process UI updates? (.NET 2.0 CF)

前端 未结 10 2203
梦谈多话
梦谈多话 2020-12-18 11:49

I want to otherwise block code execution on the main thread while still allowing UI changes to be displayed.

I tried to come up with a simplified example version of

10条回答
  •  盖世英雄少女心
    2020-12-18 12:39

    Common activities which 'block' the main thread are things like opening messages boxes or modal dialog. The main code appears to block at the MessageBox or ShowDialog call.

    The way those items work (and MessageBox is just a specialized modal dialog) is that they contain their own message pump while they're blocking.

    Although it's a nasty hack, you can do something like this in your app by looping calling Application.DoEvents() to keep the user messages pumping while you're waiting for your other task to complete. You need to be careful because all sorts of nasty things might lead from pumping messages like this - for example someone close the form or reenter your current message handler - the modal dialogs avoid this by effectively disabling input from the form which launches them.

    I did mean to say that BackgroundWorker is a better solution, if you can make it fit. I sometimes combine it with a modal 'progress dialog' to give me the background thread / message pumping and the blocking of the UI thread.

    Edit - to expand on the last bit:

    One approach I've used is to have a 'progress form' class, which takes a BackgroundWorker object as a constructor parameter, and contains handlers for the progress and completion events of the background worker which gets passed to it.

    The form which wants the work done creates the background worker and hooks up the 'work' event (can't remember what it's called right now), and then creates a progress dialog to which it passes the background worker. It then modally shows the progress dialog, which means it will wait (but pumping messages) until the progress dialog closes.

    The progress form is responsible for starting the BackgroundWorker from its OnLoad override, and closes itself when it sees the BackgroundWorker complete. Obviously you can add message text, progress bars, cancel buttons, whatever to the progress form.

提交回复
热议问题