Help me with that CrossThread?

This code is executed by many way. When it's executed by the form button it works (the button start a thread and in the loop it call this method = it works). BUT it doesn't work when I have a call to that method from my BackgroundWorker in the form.

With the following code:

private void resizeThreadSafe(int width, int height)
{
    if (this.form.InvokeRequired)
    {
        this.form.Invoke(new DelegateSize(resizeThreadSafe),
            new object[] { width, height });
    }
    this.form.Size = new Size(width, height); // problem occurs on this line
    this.form.Location = new Point(0, 0); // dummy coordinate
}

Then on the line containing this.form.Size = ... I get the following exception:

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

Why?

Answers


You need to return at the end of the if block - otherwise you'll resize it in the right thread, and then do it in the wrong thread as well.

In other words (if you'd cut and paste the code instead of a picture, this would have been easier...)

private void resizeThreadSafe(int width, int height)
{
    if (this.form.InvokeRequired)
    {
        this.form.Invoke(new DelegateSize(resizeThreadSafe,
            new object[] { width, height });
        return;
    }
    this.form.Size = new Size(width, height);
    this.form.Location = new Point(0, SystemInformation.MonitorSize // whatever comes next
}

Alternatively just put the second half of the method in an "else" block.


Need Your Help

Using Ant's xslt task in a Gradle plugin and make it find a resource

java xslt ant gradle gradle-plugin

I'm currently working on a Gradle plugin, and that plugin's JAR contains an XSL file that I'd like to use in Ant's xslt task as invoked by Gradle:

Why 2 NULL pointers do not evaluate to false?

c++ pointers null boolean

I have a relatively simple algorithm that walks an std::vector looking for two neighbouring tuples. Once the tuples left and right of the X value are found I can interpolate between them. Somehow t...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.