Working on an existing project, I've got to use WinForms (haven't worked with it for a while) and have got an issue synchronizing with the UI thread.

The design I've got to integrate with works as follows: A BackgroundWorker gets an Action as a parameter and executes it asynchronously. The action I'm working on has two parts; a core class (containing the business logic) and a GUI part being notified by the core through events if it has to request user interaction.

I've added the handle creation to the constructor of the form

if (!IsHandleCreated)
{
    //be sure to create the handle in the constructor
    //to allow synchronization with th GUI thread
    //when using Show() or ShowDialog()
    CreateHandle();
}

With this, following code works:

private DialogResult ShowDialog(Form form)
{
    DialogResult dialogResult = DialogResult.None;
    Action action = delegate { dialogResult = form.ShowDialog(); };
    form.Invoke(action);
    return dialogResult;
}

For this example, the startup location has been set to windows default.

If I change it to:

Action action = delegate { dialogResult = form.ShowDialog(ParentWindow); };

Where ParentWindow is an instance of IWin32Window and the WindowStartupLocation is set to CenterParent. I get a cross-thread exception when calling form.Invoke(action).

Cross-thread operation not valid: Control 'ActivationConfirmationForm' accessed from a thread other than the thread it was created on.

Questions:

  • Why is there a cross thread exception only when setting the startup location as CenterParent? And how do I avoid it?
  • Why is form.InvokeRequired always false?

Both are probably related!?

Edit
Report