1
public partial class JobDataDuplicatorForm : Form
{
    public JobDataDuplicatorForm(IJobDataDuplicatorEngine engine)
    {
        _engine.CopyStartedEvent += GetEventHandler(OnCopyStarted);
        _engine.CopyEndedEvent += GetEventHandler(OnCopyEnded);
        ...
    }

    private static EventHandler GetEventHandler(Action action)
    {
        return (sender, args) => action();
    }

    private void OnCopyStarted()
    {
        copyStatus.Text = "Copy progress: ";
        generateButton.Enabled = false; // Cross-thread operation not valid
    }
}

I have the following exception:

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

Can I fix the exception by changing GetEventHandler() instead of wrapping each button in different places like this

Invoke((MethodInvoker)delegate { generateButton.Enabled = false; }); ?

How can I do this?

Anatoly
  • 1,908
  • 4
  • 25
  • 47

1 Answers1

2

From your comments you said you call JobDataDuplicatorForm(IJobDataDuplicatorEngine engine) from a background thread.

Your class is a Form, any windows controls (Which includes Form) must be initially created on the UI thread or things like Invoke and InvokeRequired break. Whatever code is calling the constructor of JobDataDuplicatorForm must do that call from the UI thread.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431