Boris Rozhkovsky
Boris Rozhkovsky

Reputation: 605

C# Queue of Tasks

I need to process tasks in sequence. So this class subscribed to some events. When event is handled, asynchronous method must be added to Queue, and it might be executed when all previous tasks completed. At this moment it is realized as here: But ProccessTasks method stops working when firs event is raised.

public class class view
{
    private void ModelUpdatedEventHandler(object sender, EventArgs args)
    {
        taskQueue.Enqueue(new Task(() => Invalidate()));
    }

    private void MoveCubesEventHandler(object sender, MoveCheckerEventArgs args)
    {
        taskQueue.Enqueue(new Task(() => MoveCube(args.Move)));
    }

    private async Task Invalidate()
    {
        //code here
    }

    public async Task MoveChecker(Move move)
    {                       
        //code here
    }

    private async Task ProccessTasks()
    {
        while (true)
        {
            while (taskQueue.Count > 0)
            {
                Task task = taskQueue.Dequeue();
                await task;
            }
        }
    }

    private async void UserControl_Loaded_1(object sender, RoutedEventArgs e)
    {
        await Task.Run(() => ProccessTasks());
    }
}

Upvotes: 0

Views: 2160

Answers (1)

Servy
Servy

Reputation: 203820

The problem is that you're never starting your tasks, ever. You put unstarted tasks into the queue, and then you wait on the unstarted tasks when you pull them out.

Having said that, I would discourage you from just making that one small change. Generally, dealing with unstarted tasks is fairly error prone, as you've seen. I would suggest enqueing Action objects instead of Task objects. When you pull the action out of the queue, you can then either execute it, or if you want to maintain asynchrony, use Task.Run to run it in another thread.

You also don't need to call ProccessTasks using Task.Run. It's already asynchronous, so there's no need to run it in a background thread.

Upvotes: 1

Related Questions