Search code examples
c#channelproducer-consumersystem.threading.channels

How to pass arguments into a Channel's queue writer?


I have a background task to be completed; however, I can't write arguments to the Channel. Reason being that the writer only takes in 1 argument. How do queue a function up to be completed with arguments.

private readonly Channel<Func<double, double, string, CancellationToken, ValueTask>> _queue;

//...

public async ValueTask QueueWorkItemAsync(
    Func<double, double, string, CancellationToken, ValueTask> workItem, string args)
{
    if (workItem is null)
    {
        throw new ArgumentNullException(nameof(workItem));
    }

    // Can't pass args into WriteAsync
    await _queue.Writer.WriteAsync(workItem);
}

Solution

  • I ended up switching Channel for a ConcurrentQueue. That allowed more flexibility as to what I could put in.