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
I ended up adding to the TaskQueue:
Task<T> Enqueue<T>(Func<T> function)
{
await semaphore.WaitAsync();
try
{
return await Task.Factory.StartNew(() => function.invoke();)
}
finally
{
semaphore.Release();
}
}
And, update the host to the following:
return await queue.Enqueue(request.Execute();)
And, this is doing what I need from the WCF service. The items execute FIFO from multiple applications sending requests.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.