1
\$\begingroup\$

After getting much improvement, it´s still one issue that concerns me. And that is the sync between my 2 threads.

I use AutoResetEvent, but sadly, it has some delay with it, and would love to use something else if possible. Would be great if something could be connected to a Bool or the Queue i am using. Here is the Codes:

    SharpDX.Windows.RenderLoop.Run(form, () =>
    {

    if (Queue.TryDequeue(out TextureData))
    {
        ........
    }
    else
    {
        AutoReset.WaitOne(100);
    }
});

So there it does it´s thing, if there is something in a Queue, else it will wait on AutoReset Up till 100ms (this is to prevent the Form to totally freeze).

while (ReceiveCheck.Checked && tt1.Connected)
{
    ...........
    AutoReset.Set();
    Queue.Enqueue(tempBytes);
}

And there i simply do my work, and then tell the other thread to start, and right after i Queue my item. (why i AutoReset Before that is because of the delay, to help minimize it a bit).

Is there a way to improve this? Would be great if the other thread could just wait until there is something in the Queue and then run.

\$\endgroup\$
0
2
\$\begingroup\$
  1. When I tried to measure the delay of AutoResetEvent, I usually got less than 0.1 ms. That doesn't sounds like something you should worry about. If you're seeing larger delay, maybe it's caused by something else. It could be processing the message queue, which is what RenderLoop does between calls to Run().

  2. Calling Set() before you enqueue the item is wrong, because it has a race condition: the dequeuing thread could wake up and call TryDequeue() before you call Enqueue().

  3. In fact, the whole way you're using AutoResetEvent is wrong. If two items are enqueued quickly, then only one of them will be dequeued. Actually, this could be what's causing the delay you see, because it means there could be an ever-growing number of items in the queue just waiting for no good reason.

  4. A better way to write your code would be to use BlockingCollection<T> instead of ConcurrentQueue<T> (which I assume you're using now) and AutoResetEvent.

  5. It might be more efficient to dequeue more than one item from the queue in each call to Run(), if they are available. But probably only a limited amount, to make sure the message queue is processed too.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I actually found the Answer myself, and it´s the 4th of yours suggestions. IT works perfectly, as it´s pretty much ConcurrentQueue with AutoResetEvent inbuilt. So accepted Answer:)! \$\endgroup\$ – Zerowalker Aug 23 '13 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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