Threading Problems With Multiple Picture Boxes

I have an app that has 6 picture boxes on a windows form. I have 6 different threads running, and each one is displaying images to a separate picture box. If the threads are initiated by a file dialog box, the app works. But if the threads are originated by a FileSystemWatcher, the images don't display and I get sometimes get cross threading exceptions.

What would be the proper way for the threads to display images to the picture boxes Would delegates be useful here



Answer this question

Threading Problems With Multiple Picture Boxes

  • youngDev

    Different ways work differently.

    1) Your thread can pass references by declaring in the thread a static variable. I don't like this method, but it works.

    2) Delegates to me are the only way to fly. They're asynchronous. The thread can notify the parent when it's done, you don't have to wait for anything. This is the way to go.



  • Momchil

    You should use the Control.Invoke method if invoke is required. This can be checked by reading the Control.InvokeRequired property. Use the MethodInvoker delegate to invoke parameterless method otherwise use a other delegate or create your own.

    Here is a little example:


    public delegate void SafelySetImageHandler( PictureBox destination, Image image );

    public void SafelySetImage( PictureBox destination, Image image )
    {
    // Check if invoke is required.
    if( destination.InvokeRequired )
    {
    // Create argument array.
    Object[] args = new object[]
    {
    destination, image
    };

    // Re-call this method safely.
    SafelySetImageHandler method = new SafelySetImageHandler( SafelySetImage );
    destination.Invoke( method, args );
    return;
    }

    // Set the image.
    destination.Image = image;
    }




  • Threading Problems With Multiple Picture Boxes