![](/img/trans.png)
[英]F# asynchronous event handlers for WPF similar to C#'s async and await
[英]Async Await in F#
我將本實驗中的一些C#重寫為F#: https : //github.com/Microsoft/TechnicalCommunityContent/tree/master/IoT/Azure%20Stream%20Analytics/Session%202%20-%20Hands%20On
我正在練習6,#17 - 創建SimpleEventProcessor
類型。
我想實現CloseAsync
方法
C#
async Task IEventProcessor.CloseAsync(PartitionContext context, CloseReason reason)
{
Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason);
if (reason == CloseReason.Shutdown)
{
await context.CheckpointAsync();
}
}
我開始是這樣的:
member this.CloseAsync(context, reason) =
Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason)
match reason with
| CloseReason.Shutdown -> await context.CheckpointAsync()
| _ -> ()
但我有兩個問題:
如果值的類型為Async<'T>
,則可以在沒有任何關鍵字的情況下返回它。 如果它具有類型Task
或Task<'T>
,則可以執行|> Async.AwaitTask
。
您可以返回async { return () }
。
所以你得到這個:
member this.CloseAsync(context, reason) =
Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason)
match reason with
| CloseReason.Shutdown -> context.CheckpointAsync() |> Async.AwaitTask
| _ -> async { return () }
另一種可能性是將整個塊放在async
工作流中,並使用return!
為1並return
2:
member this.CloseAsync(context, reason) =
async {
Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason)
match reason with
| CloseReason.Shutdown -> return! context.CheckpointAsync() |> Async.AwaitTask
| _ -> return ()
}
事實上,使用異步工作流允許您刪除()
情況類似於C#:
member this.CloseAsync(context, reason) =
async {
Debug.WriteLine("Processor Shutting Down. Partition '{0}', Reason: '{1}'.", context.Lease.PartitionId, reason)
if reason = CloseReason.Shutdown then
return! context.CheckpointAsync() |> Async.AwaitTask
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.