If you try this you will see for yourself that it will not work because the BackgroundWorker
thread is not STA (it comes from the managed thread pool).
The essence of the matter is that you cannot show user interface from a worker thread1, so you must work around it. You should pass a reference to a UI element of your application (the main form would be a good choice) and then use Invoke
to marshal a request for user interaction to your UI thread. A barebones example:
class MainForm
{
// all other members here
public bool AskForConfirmation()
{
var confirmationForm = new ConfirmationForm();
return confirmationForm.ShowDialog() == DialogResult.Yes;
}
}
And the background worker would do this:
// I assume that mainForm has been passed somehow to BackgroundWorker
var result = (bool)mainForm.Invoke(mainForm.AskForConfirmation);
if (result) { ... }
1 Technically, you cannot show user interface from a thread that is not STA. If you create a worker thread yourself you can choose to make it STA anyway, but if it comes from the thread pool there is no such possibility.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…