Creating threads - Task.Factory.StartNew vs new Thread()

前端 未结 4 1483
感动是毒
感动是毒 2020-11-29 16:48

I am just learning about the new Threading and Parallel libraries in .Net 4

In the past I would create a new Thread like so (as an example):

DataInTh         


        
4条回答
  •  迷失自我
    2020-11-29 17:20

    The task gives you all the goodness of the task API:

    • Adding continuations (Task.ContinueWith)
    • Waiting for multiple tasks to complete (either all or any)
    • Capturing errors in the task and interrogating them later
    • Capturing cancellation (and allowing you to specify cancellation to start with)
    • Potentially having a return value
    • Using await in C# 5
    • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

    Note that in both cases you can make your code slightly simpler with method group conversions:

    DataInThread = new Thread(ThreadProcedure);
    // Or...
    Task t = Task.Factory.StartNew(ThreadProcedure);
    

提交回复
热议问题