11

What is the proper technique to have ThreadA signal ThreadB of some event, without having ThreadB sit blocked waiting for an event to happen?

i have a background thread that will be filling a shared List<T>. i'm trying to find a way to asynchronously signal the "main" thread that there is data available to be picked up.


i considered setting an event with an EventWaitHandle object, but i can't have my main thread sitting at an Event.WaitOne().


i considered having a delegate callback, but a) i don't want the main thread doing work in the delegate: the thread needs to get back to work adding more stuff - i don't want it waiting while the delegate executes, and b) the delegate needs to be marshalled onto the main thread, but i'm not running a UI, i have no Control to .Invoke the delegate against.


i considered have a delegate callback that simply starts a zero interval System.Windows.Forms.Timer (with thread access to the timer synchronized). This way the thread only needs to be stuck as it calls

Timer.Enabled = true;

but that seems like a hack.

In the olden days my object would have created a hidden window and had the thread post messages to that hidden windows' HWND. i considered creating a hidden control, but i gather that you cannot .Invoke on a control with no handle created. Plus, i have no UI: my object could have been created on a web-server, service, or console, i don't want there to be a graphical control appearing - nor do i want to compile a dependency on System.Windows.Forms.


i considered having my object expose an ISynchronizeInvoke interface, but then i would need to implement .Invoke(), and that's my problem.


What is the proper technique to have thread A signal thread B of some event, without having thread B sit blocked waiting for an event to happen?

7 Answers 7

11

Here's a code sample for the System.ComponentModel.BackgroundWorker class.

    private static BackgroundWorker worker = new BackgroundWorker();
    static void Main(string[] args)
    {
        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        worker.ProgressChanged += worker_ProgressChanged;
        worker.WorkerReportsProgress = true;

        Console.WriteLine("Starting application.");
        worker.RunWorkerAsync();

        Console.ReadKey();
    }

    static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        Console.WriteLine("Progress.");
    }

    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        Console.WriteLine("Starting doing some work now.");

        for (int i = 0; i < 5; i++)
        {
            Thread.Sleep(1000);
            worker.ReportProgress(i);
        }
    }

    static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Console.WriteLine("Done now.");
    }
0
3

I'm combining a few responses here.

The ideal situation uses a thread-safe flag such as an AutoResetEvent. You don't have to block indefinitely when you call WaitOne(), in fact it has an overload that allows you to specify a timeout. This overload returns false if the flag was not set during the interval.

A Queue is a more ideal structure for a producer/consumer relationship, but you can mimic it if your requirements are forcing you to use a List. The major difference is you're going to have to ensure your consumer locks access to the collection while it's extracting items; the safest thing is to probably use the CopyTo method to copy all elements to an array, then release the lock. Of course, ensure your producer won't try to update the List while the lock is held.

Here's a simple C# console application that demonstrates how this might be implemented. If you play around with the timing intervals you can cause various things to happen; in this particular configuration I was trying to have the producer generate multiple items before the consumer checks for items.

using System;
using System.Collections.Generic;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        private static object LockObject = new Object();

        private static AutoResetEvent _flag;
        private static Queue<int> _list;

        static void Main(string[] args)
        {
            _list = new Queue<int>();
            _flag = new AutoResetEvent(false);

            ThreadPool.QueueUserWorkItem(ProducerThread);

            int itemCount = 0;

            while (itemCount < 10)
            {
                if (_flag.WaitOne(0))
                {
                    // there was an item
                    lock (LockObject)
                    {
                        Console.WriteLine("Items in queue:");
                        while (_list.Count > 0)
                        {
                            Console.WriteLine("Found item {0}.", _list.Dequeue());
                            itemCount++;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No items in queue.");
                    Thread.Sleep(125);
                }
            }
        }

        private static void ProducerThread(object state)
        {
            Random rng = new Random();

            Thread.Sleep(250);

            for (int i = 0; i < 10; i++)
            {
                lock (LockObject)
                {
                    _list.Enqueue(rng.Next(0, 100));
                    _flag.Set();
                    Thread.Sleep(rng.Next(0, 250));
                }
            }
        }
    }
}

If you don't want to block the producer at all, it's a little more tricky. In this case, I'd suggest making the producer its own class with both a private and a public buffer and a public AutoResetEvent. The producer will by default store items in the private buffer, then try to write them to the public buffer. When the consumer is working with the public buffer, it resets the flag on the producer object. Before the producer tries to move items from the private buffer to the public buffer, it checks this flag and only copies items when the consumer isn't working on it.

1
  • Queue seems like an interesting class to use. Although i wouldn't want it in my situation since sometime the user can handle the entire List at once, rather than having to Dequeue individual items.
    – Ian Boyd
    Sep 23, 2008 at 21:31
1

If you use a backgroundworker to start the second thread and use the ProgressChanged event to notify the other thread that data is ready. Other events are available as well. THis MSDN article should get you started.

1
  • The BackgroundWorker class seems to be the only thing that can asynchronously sent a notification to the thread that created the object. Internally it uses the AsyncOperation object by calling asyncOperation.Post().
    – Ian Boyd
    Sep 23, 2008 at 21:28
1

There are many ways to do this, depending upon exactly what you want to do. A producer/consumer queue is probably what you want. For an excellent in-depth look into threads, see the chapter on Threading (available online) from the excellent book C# 3.0 in a Nutshell.

1
  • In producer/consumer model the main thread creates units of work that need to be performed. A background thread sits waiting for work be queued up. When a unit of work is created and event is set. That doesn't work here since the main thread is the "consumer", and it can't sit waiting for work.
    – Ian Boyd
    Sep 23, 2008 at 19:18
1

You can use an AutoResetEvent (or ManualResetEvent). If you use AutoResetEvent.WaitOne(0, false), it will not block. For example:

AutoResetEvent ev = new AutoResetEvent(false);
...
if(ev.WaitOne(0, false)) {
  // event happened
}
else {
 // do other stuff
}
1
  • How do you check if the event is signalled? i.e. when?
    – Ian Boyd
    Nov 21, 2008 at 18:22
1

The BackgroundWorker class is answer in this case. It is the only threading construct that is able to asynchronously send messages to the thread that created the BackgroundWorker object. Internally BackgroundWorker uses the AsyncOperation class by calling the asyncOperation.Post() method.

this.asyncOperation = AsyncOperationManager.CreateOperation(null);
this.asyncOperation.Post(delegateMethod, arg);

A few other classes in the .NET framework also use AsyncOperation:

  • BackgroundWorker
  • SoundPlayer.LoadAsync()
  • SmtpClient.SendAsync()
  • Ping.SendAsync()
  • WebClient.DownloadDataAsync()
  • WebClient.DownloadFile()
  • WebClient.DownloadFileAsync()
  • WebClient...
  • PictureBox.LoadAsync()
0

If your "main" thread is the Windows message pump (GUI) thread, then you can poll using a Forms.Timer - tune the timer interval according to how quickly you need to have your GUI thread 'notice' the data from the worker thread.

Remember to synchronize access to the shared List<> if you are going to use foreach, to avoid CollectionModified exceptions.

I use this technique for all the market-data-driven GUI updates in a real-time trading application, and it works very well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.