Pieter
Pieter

Reputation: 32765

Runtime error about cross-thread calls despite using invoke

I get an InvalidOperationException on this line of code:

SynchronizedInvoke(this, () => this.Opacity = this.Opacity + 0.05);

To be specific about the runtime error...

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

I used the SynchronizedInvoke method as suggested elsewhere on Stack Overflow to make sure that an invoke is used if required.

static void SynchronizedInvoke(ISynchronizeInvoke sync, Action action)
{
    // If the invoke is not required, then invoke here and get out.
    if (!sync.InvokeRequired)
    {
        // Execute action.
        action();

        // Get out.
        return;
    }

    // Marshal to the required thread.
    sync.Invoke(action, new object[] { });
}

How can this code generate a runtime error about cross-thread calls even though I use SynchronizeInvoke to avoid it?

Upvotes: 0

Views: 306

Answers (2)

Hans Passant
Hans Passant

Reputation: 941455

You'll get that when sync.InvokeRequired is false. That's not good, it should be true. Set a breakpoint on action(); and find out what is going on when you get the break.

This is the kind of code that you'd use while the form is being shown, InvokeRequired is false when the form's Handle isn't created yet. Make sure this code doesn't run too soon, you'll have to wait until either the form's OnHandleCreated() method runs or the Load event fires, whichever is easier to override.

Another simple fix is to just not test InvokeRequired, you know it should always be true since you're running this on a worker thread. Use BeginInvoke, not Invoke and the lambda won't run until the UI thread re-enters the message loop, after the form is created. And the ultimate fix, no point in burning up a thread just to fade a form, use a winforms Timer. Saves you a megabyte.

Upvotes: 2

TimD
TimD

Reputation: 342

I don't think lambda expressions are thread safe

Upvotes: -1

Related Questions