GCD serial queue functionality in C#?

Status
Not open for further replies.
I've got something I need to do and I'm familiar with GCD so I know how to do what I want there. The problem being that I need to do this in C# (VS2013) and I pretty much never use C#. I've paid enough attention to it so I know about things like async/await but this and other things I've found via Google don't do quite what I want as far as I can tell.

Basically I have a bunch of tasks which I need to execute serially, and I want them to occur asynchronously in the background. But the main thread cannot wait while, for example, a BackgroundWorker.IsBusy(): the tasks must simply queue up in the background while the main thread continues on doing other things.

Code:
dispatch_queue_t background = dispatch_queue_create("background", DISPATCH_QUEUE_SERIAL);

dispatch_async(background, ^{
  /* task which I don't want to block my main
     thread, but which must execute serially
     with other background tasks */
});

OtherStuff();
dispatch_async(background, ^{ /* ... */ });
OtherStuff();
dispatch_async(background, ^{ /* ... */ });
OtherStuff();

Since I'm only creating background tasks from a single thread it looks like I could do something like:

Code:
var background = new Task(() => {});
background.Start();

background = background.ContinueWith(t => { /* ... */ });
OtherStuff();
background = background.ContinueWith(t => { /* ... */ });
OtherStuff();

Is there a better way? Am I right that this wouldn't work with multiple threads queuing tasks?
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
What you want is in BlockingCollection<T>.

Code:
private BlockingCollection<WorkItem> workQueue = new BlockingCollection<WorkItem>();

private Task backgroundWorkQueueTask = null;

private CancellationTokenSource backgroundWorkCancellationSource = new CancellationTokenSource();

public SomeClassConstructor()
{
   this.backgroundWorkQueueTask = Task.Run(async() =>
     {
        foreach (var workItem in this.workQueue.GetConsumeringEnumberable(this.backgroundWorkCancellationToken.Source))
        {
            await workItem.ExecuteAsync();  // you'll have to define this, obviously
        }
     });
}

public void EnqueueWorkItem(WorkItem workItem)
{
    this.workQueue.Add(workItem);
}

public void StopBackgroundWork(bool graceful) // like on app exit
{
    this.workQueue.CompleteAdding();
    if (!graceful)
    {
       this.backgroundWorkCancellationSource.Cancel();
    }
}

Edit: also keep in mind that you'll need some sort of global exception handler. WinForms/ASP.NET etc. don't take kindly to unhandled exceptions from background threads percolating up and not being handled. Look for some sort of "UnhandledExceptionHandler" event to hook into.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
[url=http:/civis/viewtopic.php?p=27481849#p27481849:jr9ro6hu said:
krimhorn[/url]":jr9ro6hu]
[url=http:/civis/viewtopic.php?p=27481497#p27481497:jr9ro6hu said:
Pont[/url]":jr9ro6hu]What you want is in BlockingCollection<T>.
So is there something special about the BlockingCollection<T> that prevents the "Collection has been modified" error when you Enqueue an item when the collection's iterated over?
Yes. It's designed specifically for being used in producer/consumer scenarios.

You'll notice you're doing foreach on workQueue.GetConsumingEnumerable. (which someone got auto-corrected to GetConsumeringEnumerable in my initial post).
 

krimhorn

Ars Legatus Legionis
39,865
[url=http:/civis/viewtopic.php?p=27482445#p27482445:2dfm3p5j said:
Pont[/url]":2dfm3p5j]
[url=http:/civis/viewtopic.php?p=27481849#p27481849:2dfm3p5j said:
krimhorn[/url]":2dfm3p5j]
[url=http:/civis/viewtopic.php?p=27481497#p27481497:2dfm3p5j said:
Pont[/url]":2dfm3p5j]What you want is in BlockingCollection<T>.
So is there something special about the BlockingCollection<T> that prevents the "Collection has been modified" error when you Enqueue an item when the collection's iterated over?
Yes. It's designed specifically for being used in producer/consumer scenarios.

You'll notice you're doing foreach on workQueue.GetConsumingEnumerable. (which someone got auto-corrected to GetConsumeringEnumerable in my initial post).
My brain transposed that part to GetConsumeringEnumerator (understanding the typo that existed otherwise).
 
Status
Not open for further replies.