0

I'm not to sure about something about EventWaitHandle.Set. When called from within current thread and there is another thread waiting for the event, do the current thread get to sleep so that other thread gets to run (ASAP)?

I'm asking because in some of my code I have to add some object to a "threads shared" queue and that operation has really to go as quick as possible. But in the other thread where that queue is being used, speed is "not required". So I'm proceeding like this:

        // Speed "not required"
        mailThread = new Task(() =>
        {
            for (; ; )
            {
                MailMessage mail;
                pushMailLockMREvt.WaitOne();
                {
                    if (mails.Count == 0)
                    {
                        mail = null;
                    }
                    else
                    {
                        mail = mails.Dequeue();
                    }
                }
                pushMailLockMREvt.Set(); // Does this put current on sleep on lower it's priority??

                if (mail != null)
                {
                    try
                    {
                        MailClient.Send(mail);
                    }
                    catch (Exception exe)
                    {
                    }
                }
                else
                {
                    mailSem.WaitOne();
                }
            }
        });

        [...]

        // Speed required
        var task = new Task(() =>
        {
            pushMailLockMREvt.WaitOne(); // ASAP please...
            {
                mails.Enqueue(mailMessage);

                if (mails.Count == 1)
                {
                    mailSem.Set();
                }
            }
            pushMailLockMREvt.Set();
        });
4

1 回答 1

2

No, the current thread will not sleep just because it signals the wait handle. But it may relinquish the rest of its timeslice (that's pretty subtle and low-level and isn't something you should rely on). You should not need to take any special action.

It is probably the case that the thread that has just finished waiting will get a brief boost in thread priority.

See this documentation for the Windows API function SetThreadPriorityBoost() from which I quote:

When a thread is running in one of the dynamic priority classes, the system temporarily boosts the thread's priority when it is taken out of a wait state.

Also see this documentation.

So the thread that just woke up from the wait should (normally) get a small boost. I'm not totally sure that this also applies to managed threads, but I seem to remember reading somewhere that it does. I can't find the source of that, though.

于 2013-05-06T09:24:55.813 回答