spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories

Pausable & resumable async task queue


I got this working and thought I should outline my solution here.

It turns out my use of cancellation tokens was a little haphazard, which was preventing this class from functioning as intended. For example, the following issues were relevant:

  1. If Cancel was called after the last cancellation check had passed in the command, a new command would be loaded (along with its own new cancellation token), and as such the cancel call would have been lost / ignored. This was solved with if (_curCommand.Cts.Token.IsCancellationRequested) return; right after _queue.Dequeue();.

  2. After a cancel had been called, if the command were to be resumed later, then it would need a new cancellation token (otherwise the existing one with cancel = true would still be active). The line _curCommand.InvalidateCancellationToken(); does this by setting the token to null, and then my command refreshes the token when next called.

The full code I used:

public class WqController
{
    private readonly Queue<ICommand> _queue
= new Queue<ICommand>();
    private Task _queueProcessor;
    private ICommand _curCommand;

    public void Enqueue(ICommand command)
    {
        _queue.Enqueue(command);

        if (_queueProcessor == null)
_queueProcessor = ProcessQueue();
    }

    private async Task ProcessQueue()
    {
        try
        {
            while (_queue.Count != 0)
            {
                _curCommand = _queue.Peek();

                try
                {
                    await Task.Run(() =>
_curCommand.Execute());
                }
                catch (OperationCanceledException)
                {
                   
_curCommand.InvalidateCancellationToken();
                    Console.WriteLine("QUEUE
PAUSED");
                    return;
                }
                catch (Exception)
                {
                    Console.WriteLine("FAILED TO
EXECUTE COMMAND");
                }
                _queue.Dequeue();
                if
(_curCommand.Cts.Token.IsCancellationRequested)
return;
            }
        }
        finally
        {
            _queueProcessor = null;
            _curCommand = null;
        }
    }

    public async Task Cancel()
    {
        _curCommand.Cts.Cancel(true);
        await _queueProcessor;
    }

    public void Resume()
    {
        _queueProcessor = ProcessQueue();
    }
}

This all seems to work very smoothly now, and is a big improvement on the Background worker queue implementation I had been using prior.


Categories : C#

Related to : Pausable & resumable async task queue
Client Not read remote MSMQ queue, but can send to remote queue
Things you might try: Changing queue permissions - see here, try setting permission to "Everyone" (for the test only). Try setting AllowNonauthenticatedRPC in registry - details here

Categories : C#
How to tell if Queue size is greater than max int?
Technically, I don't think you can, at least not without modifying the queue. The size method inherited from collections will return maxint if there are more elements than that but it will also return that if there are exactly that many elements. So, other than extracting an element and seeing if the size changes, there's no other way. That doesn't stop you creating your own queue (with a long

Categories : Java
About queue and standard deviation
You can use your efficient method for the mean also for the standard deviation because of the formula std dev = sqrt(E(x^2)-E(x)^2) (proof on wikipedia). In other words, keep track of the sum of the squares of your values (e.g. in variable sum_of_squares), and keep track of the sum of the values (e.g. in variable sum_of_values). In both cases you can update the variable in O(1) by adding one val

Categories : Algorithm
How do I get a Priority Queue to re-sort itself
The problem here is, that you need to change other elements in the data structure. You cannot just iterate over them, and do operations on them, this will change the ordering of elements. The best way to do this, is to create a vector of the current structure, do operations on the vector, and reinsert them. If speed is what troubles you, this operations have the same time complexity as the code

Categories : Java
"Missing argument parameter 'queue' in call"
runBlock expects a block not a method, you can define a block and call the method from there: SKAction.runBlock({ () -> Void in self.spawnObstacle()}) or try just SKAction.runBlock({self.spawnObstacle()}) EDIT: this is not the cause of the crash

Categories : IOS
Recently Add
Get Existing Outlook Addin Information from External C# Application
What's the best way to share an instance of an object across many objects?
Searching a enum description containing a slash
C# how to properly make a http web GET request
Get ComboBox selected value form Form1 to another Form2
Pixel Format conversion
Why does my download queue break when called faster after each other?
How to define XML namespaces to be incuded in the header of XML request which will be send via invoke of a Web Service call?
eventlog source - string/message table lookup failed
What is the idea behind IIdentity and IPrincipal in .NET
How can the Wix Installer distinguish target builds?
Verifying if method was called with Moq
Send json data to SQL Server 2008
Cannot validate in MVC 5 authentication with both UserName and Email
Unioning two LINQ queries
How to block a number in Twilio
Pass object attribute to controller
C# nHibernate programatically set db password
How to add node at mouse click location on canvas?
Register boolean in Container
ASP MVC or/and Networking issues
Managing Single Quotes while calling on a Stored Procedure
Connection String to connect a SQL Server using another windows account
DynamicTableEntity PartitionKey and RowKey
The property content is set more than once.. WPF
How to change asp:ListView DataPager page from codebehind (c#)
Case-insensitive "contains" in Linq
Bootstrap Button_Click Event Not Firing
catch OnVisibilityChanged events
In C#, SQL connection is printing: 'System.Data.SqlClient.SqlDataReader'
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.