Skip to content

Awaiting a queue not working as expected. #4

@RossMetacraft

Description

@RossMetacraft

Hello! I came across this library while searching for a way to run tasks in a serial fashion to avoid any concurrency issues in my application. It looks like it will work perfectly. In your Examples and Programming Models Wiki page, you demonstrate a very simple and elegant way of achieving serialization of tasks by simply awaiting the queue at the start of each task method. I tried doing this in a simple proof-of-concept application and it does not appear to be working as I expect. I'm either doing something wrong, or this library isn't actually designed to do what I thought. I'm hoping you can set me straight.

In my simple test app, I have a window with two buttons. One button adds random integers to a list. The other button iterates over the list, printing the values to the debug console. It sleeps for 500 ms between prints. I'm hoping to be able to populate the list with a few integers, then iterate the list, and try to add another integer to the list while the list is being iterated, and avoid the usual InvalidOperationException due to the collection being modified during iteration.

Here is the window's code-behind file:

using System.Windows;
using Dispatch;

namespace SerialQueueTest;

public partial class MainWindow : Window
{
	private readonly SerialQueue mSerialQueue = new();
	private readonly List<int> mList = [];

	public MainWindow()
	{
		InitializeComponent();
	}

	private async void Iterate_Click(object sender, RoutedEventArgs e)
	{
		await IterateInts();
	}

	private async void Add_Click(object sender, RoutedEventArgs e)
	{
		await AddInt();
	}

	private async Task IterateInts()
	{
		await mSerialQueue;
		foreach (int i in mList) {
			System.Diagnostics.Debug.WriteLine($"iterating: {i}");
			await Task.Delay(500);
		}
	}

	private async Task AddInt()
	{
		await mSerialQueue;
		int i = Random.Shared.Next();
		System.Diagnostics.Debug.WriteLine($"adding {i}");
		mList.Add(i);
	}
}

To run the test, I launch the app, click the "Add" button 5 times to populate the list with 5 random integers. I then click the "Iterate" button, and while it is iterating, I click the "Add" button again to attempt to add a 6th integer to the list. This causes the usual InvalidOperationException with the message "Collection was modified; enumeration operation may not execute."

Am I missing something, or does the lib not behave the way I'm expecting here?

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions