Task Parallel Library vs Async Workflows

前端 未结 2 1337
悲&欢浪女
悲&欢浪女 2020-12-04 16:53

I have some stuff written in c# that executes concurrent code, making heavy use of the Task Parallel Library (Task and Future continuation chains).

I\'m now portin

2条回答
  •  有刺的猬
    2020-12-04 17:17

    In 4.0 I would say:

    • If your function is sequential, use Async workflows. They simply read better.
    • Use the TPL for everything else.

    It's also possible to mix and match. They've added support for running a workflow as a task and creating tasks that follow the async Begin/End pattern using TaskFactory.FromAsync, the TPL equivalent of Async.FromBeginEnd or Async.BuildPrimitive.

    let func() =
        let file = File.OpenRead("foo")
        let buffer = Array.zeroCreate 1024
        let task1 = Task.Factory.FromAsync(file.BeginRead(buffer, 0, buffer.Length, null, null), file.EndRead)
        task1.Start()
    
        let task2 = Async.StartAsTask(file.AsyncRead(1024))
        printfn "%d" task2.Result.Length
    

    It's also worth noting that both the Async Workflows runtime and the TPL are going to create an extra kernel primitive (an Event) and use WaitForMultipleObjects to track I/O completion, rather than using completion ports and callbacks. This is undesirable in some applications.

提交回复
热议问题