回答您问题的一部分:“如果 Begin 函数需要一些参数,我该如何使用 FromBeginEnd?”
您可以通过闭包的魔力来做到这一点。这里有一些例子。如您所见,扩展方法接受参数,但将匿名函数传递给Async.FromBeginEnd,该函数与FromBeginEnd 预期的签名相匹配。额外的参数在闭包中被捕获并传递到匿名函数内部的真实BeginXyz。
您还可以使用 FromBeginEnd 的重载,它首先采用附加参数,然后是指向 Begin/End 函数的指针,就像我在下面的 AsyncGetReadStream 方法中所做的那样 - 但是当有多个重载时BeginXyz 我很难让它工作,所以我对大多数人使用了闭包。
open System
open System.Data.Services.Client
type System.Data.Services.Client.DataServiceContext with
member this.AsyncExecute<'a> (uri:Uri) =
Async.FromBeginEnd((fun (cb, state) -> this.BeginExecute<'a>(uri, cb, state)),
(fun iar -> this.EndExecute<'a>(iar) :?> QueryOperationResponse<'a>))
member this.AsyncExecute<'a> (continuation:DataServiceQueryContinuation<'a>) =
Async.FromBeginEnd((fun (cb, state) -> this.BeginExecute<'a>(continuation, cb, state)),
(fun iar -> this.EndExecute<'a>(iar) :?> QueryOperationResponse<'a>))
member this.AsyncExecuteBatch ([<ParamArray>] queries : DataServiceRequest[]) =
Async.FromBeginEnd((fun (cb, state) -> this.BeginExecuteBatch(cb, state, queries)), this.EndExecuteBatch)
member this.AsyncLoadProperty (entity:obj, propertyName:string) =
Async.FromBeginEnd((fun (cb, state) -> this.BeginLoadProperty(entity, propertyName, cb, state)),
this.EndLoadProperty)
member this.AsyncLoadProperty (entity:obj, propertyName:string, continuation:DataServiceQueryContinuation) =
Async.FromBeginEnd((fun (cb, state) -> this.BeginLoadProperty(entity, propertyName, continuation, cb, state)),
this.EndLoadProperty)
member this.AsyncLoadProperty (entity:obj, propertyName:string, nextLinkUri:Uri) =
Async.FromBeginEnd((fun (cb, state) -> this.BeginLoadProperty(entity, propertyName, nextLinkUri, cb, state)),
this.EndLoadProperty)
member this.AsyncSaveChanges () =
Async.FromBeginEnd(this.BeginSaveChanges, this.EndSaveChanges)
member this.AsyncSaveChanges (options:SaveChangesOptions) =
Async.FromBeginEnd((fun (cb, state) -> this.BeginSaveChanges(options, cb, state)),
this.EndSaveChanges)
member this.AsyncGetReadStream (entity:obj, args:DataServiceRequestArgs) =
Async.FromBeginEnd(entity, args, this.BeginGetReadStream, this.EndGetReadStream)
type System.Data.Services.Client.DataServiceQuery with
member this.AsyncExecute () =
Async.FromBeginEnd(this.BeginExecute, this.EndExecute)