I found this class in another answer Best way in .NET to manage queue of tasks on a separate (single) thread.
I wanted to try it out, but the syntax is a bit strange to me. Trying to just kick off a dummy task that returns a single int. I can't get this to compile, not sure what the syntax problem is.
m_TaskQueue.Enqueue<int>(
() => { return 1; }
);
Compiler error:
Cannot convert lambda expression to delegate type
System.Func<System.Threading.Tasks.Task<int>>
because some of the return types in the block are not implicitly convertible to the delegate return type
Class from other answer:
public class TaskQueue
{
private SemaphoreSlim semaphore;
public TaskQueue()
{
semaphore = new SemaphoreSlim(1);
}
public async Task<T> Enqueue<T>(Func<Task<T>> taskGenerator)
{
await semaphore.WaitAsync();
try
{
return await taskGenerator();
}
finally
{
semaphore.Release();
}
}
public async Task Enqueue(Func<Task> taskGenerator)
{
await semaphore.WaitAsync();
try
{
await taskGenerator();
}
finally
{
semaphore.Release();
}
}
}
To add to the other answers which suggest using Task.FromResult
to create a task, you could also use an async lambda expression - this would be useful if you want to use await
within the body of the lambda expression:
m_TaskQueue.Enqueue<int>(
async () => {
await Task.Delay(1000); // For example
return 1;
}
);
See more on this question at Stackoverflow