“Object is currently in use elsewhere” exception when setting image in picturebox

With the title, there are several questions but none of them could help me or direct me to solve my problem.

I am building a real-time or near-real-time imaging application with C# winform.

But assigning an image to PictureBox in winform

pictureBox.Image = image; 

basically gives a random exception Object is currently in use elsewhere. in 5-20 mins.

I searched materials on this issue but couldn't find a right solution. The error occurred when program was simply setting the image to display from a queue. So there is no way that image can be used in other thread.

At this point, I am not sure winform is right platform for an imaging application. Do I have to move to another platform such as WPF?

I need advice from experienced.

Update: As Nathanael pointed out, I could access picturebox from multithreads so I assumed that multithreads can access picturebox's image. So when I changed the line above to following, I don't get any error any more.

      private void SetImage(Bitmap image) 
      {
            if (this.pictureBox.InvokeRequired)
            {
                SetImageCallback callback = new SetImageCallback(SetImage);
                this.BeginInvoke(callback, new object[] { image });
            }
            else
            {
                pictureBox.Image = image;
            }
      }

Answers


If I understood your question correctly, you're accessing this picture box from multiple threads. WinForms uses GDI+ under the hood, which is not thread safe. WinForms does not force you to only access UI objects from the thread they were created on. It let's you do it, but you'll eventually have errors, as you've discovered.

Try posting messages to your GUI thread from your worker threads to have the GUI thread update the picture. This should solve the error you're seeing.

You'll have similar threading problems if you move to WPF. WPF strictly enforces that only the thread that created a UI object can make modifications to it. In WPF you can use the Invoke methods to have the correct thread manipulate your picture box.

Otherwise as stated the performance difference between the two won't be significant. You should consider if you need or prefer immediate mode drawing to retained mode. Forms is immediate, WPF retained.


Need Your Help

Constructing a list of function applications

scala haskell

I have a Haskell function which I would like to translate into Scala. The Haskell function is:

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.