I am trying to create a task scheduler / ordered scheduler in conjunction with using TaskFactory.FromAsync .
I want to be able to disable web service requests (using FromAsync to use I / O completion ports), but keep them in order and only perform one run at any time.
I am not currently using FromAsync , so I can do TaskFactory.StartNew(()=>api.DoSyncWebServiceCall()) and rely on the OrderedTaskScheduler used by TaskFactory to ensure that only one request is inactive.
I assumed that this behavior will remain when using the FromAsync method, but it is not:
TaskFactory<Stuff> taskFactory = new TaskFactory<Stuff>(new OrderedTaskScheduler()); var t1 = taskFactory.FromAsync((a, s) => api.beginGetStuff(a, s), a => api.endGetStuff(a)); var t2 = taskFactory.FromAsync((a, s) => api.beginGetStuff(a, s), a => api.endGetStuff(a)); var t3 = taskFactory.FromAsync((a, s) => api.beginGetStuff(a, s), a => api.endGetStuff(a));
All of these beginGetStuff methods beginGetStuff called in a FromAsync call (therefore, although they are sent in order, at the same time, n api calls are encountered).
There is FromAsync overload that accepts TaskScheduler:
public Task FromAsync( IAsyncResult asyncResult, Action<IAsyncResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler )
but the docs say:
TaskScheduler, which is used to schedule a task that runs the end method.
And as you can see, it accepts the already built IAsyncResult , not Func<IAsyncResult> .
Does this mean that the FromAsync custom method FromAsync or am I missing something? Can anyone suggest where to start this implementation?
Greetings
EDIT:
I want to distract this behavior from the caller, so in accordance with the behavior of the TaskFactory (with a specialized TaskScheduler ) I need the Task to be returned immediately - this Task not only encapsulates FromAsync Task, but also the sequence of this task while it is waiting for its progress.
One possible solution:
class TaskExecutionQueue { private readonly OrderedTaskScheduler _orderedTaskScheduler; private readonly TaskFactory _taskFactory; public TaskExecutionQueue(OrderedTaskScheduler orderedTaskScheduler) { _orderedTaskScheduler = orderedTaskScheduler; _taskFactory = new TaskFactory(orderedTaskScheduler); } public Task<TResult> QueueTask<TResult>(Func<Task<TResult>> taskGenerator) { return _taskFactory.StartNew(taskGenerator).Unwrap(); } }
However, this uses the thread while FromAsync is called. Ideally, I did not need to do this.