patterncsharpMinor
Removing this odd while(true) for checking the queue
Viewed 0 times
thisthewhileremovingcheckingtrueforqueueodd
Problem
I was reviewing some WPF code I've written in C# last year.
The scenario is the following:
-
I've a workerprocess that checks if there's some item in the queue and add them to a list that's bound to a grid
//That's used to show only filtered items (Error/Warning....)
How can I remove this
The scenario is the following:
- I've got a usercontrol that show usermessages and it's docked in the bottom of the application's workspace
- I've got a ConcurrentQueue that receives message via a IMessageMediator (from Catel, but's irrilevant how data are pushed)
-
I've a workerprocess that checks if there's some item in the queue and add them to a list that's bound to a grid
private readonly ConcurrentQueue queue;
private readonly List dataItems;
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
if (!queue.IsEmpty)
{
UserMessage message;
while (queue.TryDequeue(out message))
{
dataItems.Add(message);
}
RaisePropertyChanged(() => FilteredDataItems);
RaisePropertyChanged(() => ErrorCountMessage);
RaisePropertyChanged(() => WarningsCountMessage);
}
Thread.Sleep(500);
}
}//That's used to show only filtered items (Error/Warning....)
public IEnumerable FilteredDataItems
{
get
{
if (!enabledFilters.Any())
return dataItems;
return dataItems.Where(x => enabledFilters.Contains(x.LogMessageType));
}
}How can I remove this
while(true) and the ugly/odd Thread.Sleep(500)?Solution
It sounds like you are sleeping only to avoiding busy waiting on the queue too frequently.
How about following the suggestion in this SO answer:
https://stackoverflow.com/a/5014271/2268996
so that you use the blocking Take method in your worker with code like this:
You will still have the
How about following the suggestion in this SO answer:
https://stackoverflow.com/a/5014271/2268996
so that you use the blocking Take method in your worker with code like this:
while (true)
{
UserMessage m = blockingQueue.Take();
dataItems.add(m);
RaisePropertyChanged(() => FilteredDataItems);
... (no need to sleep here)...
}You will still have the
while (true) but not the Thread.sleep(...) call. Will that work for your situation?Code Snippets
while (true)
{
UserMessage m = blockingQueue.Take();
dataItems.add(m);
RaisePropertyChanged(() => FilteredDataItems);
... (no need to sleep here)...
}Context
StackExchange Code Review Q#104240, answer score: 4
Revisions (0)
No revisions yet.