I have a class with event-based asynchronous operation(EAP). I can create a task based on it as it described here.
When I use EAP:
my thread -> calls method -> which creates thread -> in which it does something.
When I create task I suspect that:
my thread -> creates task -> which creates thread -> which calls method -> which creates thread -> in which it does something.
Is it true?
EDIT:
Offcourse task will not create a thread – it will take thread from the thread pool if needed. But will it be taken and will I have to spent valuable extra thread from the thread pool?
To know exactly what’s going to happen, I would need to see your specific code, including how would you use the resulting
Task.But in general, if you wrap EAP into a
TaskusingTaskCompletionSource, it won’t use up another thread from the pool, because there is no code to be executed.If you mean what would happen if you used
ContinueWith()on thatTask, then that depends on whether you setTaskContinuationOptions.ExecuteSynchronouslyor not. If you don’t set it, the continuation will run on a “new” thread taken from the pool. If you do set it, it will run on the same thread that sets the result of theTask. (You should useExecuteSynchronouslyonly for very short continuations.)But whether the continuation will take a new thread from the pool or whether it uses a thread that was taken from the pool by someone else doesn’t matter much. What does matter is whether there will be any thread blocking until the operation completes. And in both cases, that’s not going to happen.