We help IT Professionals succeed at work.

is backgroundworker.IsBusy property thread safe?

CodingCat
CodingCat asked
on
hi, experts,

I have a backgroundworker declared in the main thread:

            bkworker = new BackgroundWorker { WorkerSupportsCancellation = true };
            bkworker.DoWork += new DoWorkEventHandler(bkworker_DoWork);
            bkworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bkworker_RunWorkerCompleted);

I have a camera which sends in images periodically, once an image arrives, I would like to do some image processing with the backgroundworker:

        void camera_ImageArrived(object sender, ImageEventsArgs e)
        {
            if (!bkworker.IsBusy)
            {
                augmentedImg = e.Image;
                bkworker.RunWorkerAsync();
            }
        }

The idea is that when a new image arrives, if the backgroundworker has finished processing the previous image, then start processing the new image, if not, ignore the new image.

after running the program for a while, I got this error message:

A first chance exception of type 'System.InvalidOperationException' occurred in System.dll

Additional information: This BackgroundWorker is currently busy and cannot run multiple tasks concurrently.

This indicates that the bkworker is busy, but bkworker.RunWorkerAsync() should only be executed when bkworker is not busy.  What's the problem?
Comment
Watch Question

Full Stack .NET Developer
Commented:
Hello, try:
        void camera_ImageArrived(object sender, ImageEventsArgs e)
        {
            lock (bkworker)
            {
                if (!bkworker.IsBusy)
                {
                    augmentedImg = e.Image;
                    bkworker.RunWorkerAsync();
                }
            }
        }

Open in new window

Author

Commented:
yea, that works. Thanks
Carlos VillegasFull Stack .NET Developer

Commented:
Glad to help :)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.