1

I have a worker thread in my socket server. When I set to the lowest priority, everything works find but it is slow. When I set the priority to Normal, it is much faster but when there is not work and it is in a while loop checking for an item to be added to the queue list, it still hogs up the cpu usuage and my VM slows down. I an new at thread management. How do I use a Mutex or Monitor to make the thread sleep or wait until there is work in the queue.

m_workerThread = new Thread(new ThreadStart(ProcessQueueLogs));
m_workerThread.Priority = ThreadPriority.Lowest;
m_workerThread.Start();

private void ProcessQueueLogs()
{
    try
    {
        while (!m_stopServer)
        {
            if (m_socketListenersList.Count > 0)
            {
                //Logger.WiteLog("ltsserver getting socketlistener from queue");
                // get the first socket in the list
                LTSSocketListener workerSocket = RequestQueue(null, false);
                //LTSSocketListener workerSocket = (LTSSocketListener)m_socketListenersList[0];

                if (workerSocket != null)
                {
                    // start the socket to process the request
                    workerSocket.StartProcessingRequest();

                    // close the socket
                    workerSocket.CloseSocketListener();

                    //Logger.WriteLog("ltsserver closing socketlistener");

                    // remove of the socket queue list
                    RequestQueue(workerSocket, false);
                    //m_socketListenersList.Remove(workerSocket);
                }
            }
        }
    }
    catch (SocketException e)
    {
        EventLog.WriteEntry(m_eventSource, e.Message.ToString());
        EventLog.WriteEntry(m_eventSource, e.Message.ToString(),               EventLogEntryType.Error, 234);
    }
}

Any help is appreciated.

4

2 回答 2

1

最简单的解决方案是使用BlockingCollectionC# 4.0:对方法的调用Take()将阻塞,直到将某些内容添加到队列中,让您完全避免使用同步原语。

于 2012-05-17T16:58:04.847 回答
0

Use Monitor.Wait() where you want to wait.

while (!ThereIsWork)
    Monitor.Wait(_lockerObject);

Use Monitor.Pulse() or Monitor.PulseAll() elsewhere (on another thread) to wake up the Monitor.Wait, and check the ThereIsWork condition again:

Monitor.Pulse(_lockerObject);

See here for a complete example: https://stackoverflow.com/a/530228/102937

于 2012-05-17T16:57:50.073 回答