// Waits for a packet using an already generated WaitRequest. Will block
        // the calling thread until a matching packet comes in.
        // Returns the first matching packet.
        public BluetoothPacket waitForPacket(WaitRequest req)
        {
            bool matches = false;

            BluetoothPacket ret = null;

            // Acquire a lock on the unprocessed packet queue to determine whether
            // its necessary to block. Might already have a matching packet queued up.
            lock (queue)
            {
                for (int i = 0; i < queue.Count; i++)
                {
                    if (queue[i].matchesHead(req.packetHead))
                    {
                        matches = true;
                        ret = queue[i];
                        queue.RemoveAt(i);
                        break;
                    }
                }

                // No matches, add a wait request.
                if (!matches)
                {
                    waitRequests.Add(req);
                }
            }
            if (matches) return ret;

            // Block caller
            req.Handle.WaitOne();
            return req.actualPacket;
        }
        public void init()
        {
            packets = new List<BluetoothPacket>();
            filterRequest = new WaitRequest(filterType);

            newItemEvent = new AutoResetEvent(false);
            BackgroundWorker filterWorker = new BackgroundWorker();
            filterWorker.DoWork += new DoWorkEventHandler(filterLoop);

            BackgroundWorker termWorker = new BackgroundWorker();
            termWorker.DoWork += new DoWorkEventHandler(terminationLoop);

            filterWorker.RunWorkerAsync();
            termWorker.RunWorkerAsync();
        }
 // Get rid of a wait request
 public bool removeWaitRequestFromQueue(WaitRequest req)
 {
     bool ret = false;
     lock (queue)
     {
         ret = waitRequests.Remove(req);
     }
     return ret;
 }