locked
Good case for Task.Factory.StartNew? RRS feed

  • Question

  • Imagine an IIS hosted WCF service with an operation that takes a synchronous request from a client. Further assume that the processing of that request will require a number of independent IO bound calls to other servers/services to fulfill, e.g. multiple databases, files on disks or other web services. None of these calls are dependent on another but all must be completed before a response can be returned to the client. This seems like a good candidate for the use of Task.Factor.StartNew where each separate IO bound call is made using Task.Factory.StartNew, the returned tasks are stored in a List<Task>, Task.WhenAll is used on the List, the returned data is processed and the response is sent to the client.

    In the case of a high-volume server would this in fact be a good case for Task.Factory.StartNew or is this going to actually be detrimental to performance compared with simply processing each call in series.


    Friday, May 3, 2013 10:51 PM

Answers

  • This is actually poor for performance.  Each call to T.F.StartNew will use a ThreadPool thread.  This will cause it to (potentially) speed up that particular request, but reduce the overall performance of the server as a whole.

    If the calls are all IO bound calls, it'd be better to implement the server side as an async method, and then use normal async IO calls to each of the calls, and return when they're all complete.

    Note that this is a LOT easier in .NET 4.5, since you can just make your WCF call return Task<T>, and use await Task.WhenAll(..) on the individual IO calls.  This gives you all of the benefits (full asynchrony) without using extra threads.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by Dane Vinson Saturday, May 4, 2013 5:03 AM
    Friday, May 3, 2013 11:17 PM

All replies

  • This is actually poor for performance.  Each call to T.F.StartNew will use a ThreadPool thread.  This will cause it to (potentially) speed up that particular request, but reduce the overall performance of the server as a whole.

    If the calls are all IO bound calls, it'd be better to implement the server side as an async method, and then use normal async IO calls to each of the calls, and return when they're all complete.

    Note that this is a LOT easier in .NET 4.5, since you can just make your WCF call return Task<T>, and use await Task.WhenAll(..) on the individual IO calls.  This gives you all of the benefits (full asynchrony) without using extra threads.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by Dane Vinson Saturday, May 4, 2013 5:03 AM
    Friday, May 3, 2013 11:17 PM
  • Thanks for the reply.
    Saturday, May 4, 2013 5:05 AM