In modernizing, I'm trying to update legacy libraries to use a client-side WCF service. The following is close to what I need, but I can't figure out how to add the created task to a queue that will only process one request at a time.
[ServiceContract(Name="MyService", SessionMode=Session.Required]
public interface IMyServiceContract
{
[OperationContract()]
Task<string> ExecuteRequestAsync(Action action);
}
public class MyService: IMyServiceContract
{
// How do I get this piece in a task queue?
public async Task<string> ExecuteRequestAsync(Request request)
{
return await Task.Factory.StartNew(() => request.Execute();)
}
}
I've looked at TaskQueue's that Servy shared (Best way in .NET to manage queue of tasks on a separate (single) thread). But, I'm having trouble combining the two into something that works. When I attempt to add my task to the TaskQueue below, the task never runs. I know I'm missing something, so any help is greatly appreciated.
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();
}
}
}
Thanks