从C#引用异步F#的数据类型 [英] Referencing Asynchronous F# datatype from C#

查看:100
本文介绍了从C#引用异步F#的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建的返回此数据类型的F#库

I created a F# library that returns this datatype

FSharpAsync<IEnumerable<Tupel<DateTime,string>>>

我如何访问 FSharpAsync 的类型,这样我可以通过从C#中的元组枚举和打印出来的内容?

How do I access the FSharpAsync type so I can enumerate through the tuple from C# and print out the content?

推荐答案

一般不推荐它暴露F#的类型,如 FSharpAsync 在一个公共接口将使用通过C#客户端(见<一href=\"http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/fsharp-component-design-guidelines.pdf\">F#组件的设计准则)。您可以使用 Async.StartAsTask (在F#侧)露出运营为任务&LT; T&GT; 即容易从C#中使用。

It is generally not recommended to expose F# types such as FSharpAsync in a public interface that will be used by C# clients (see F# component design guidelines). You can use Async.StartAsTask (on the F# side) to expose the operation as a Task<T> that is easy to use from C#.

其实,我也有一个名为类型更换元组(捕获的数据结构的意思)。元组可在C#中使用,但它们不是在C#惯用

In fact, I would also replace the tuple with a named type (that captures the meaning of the data structure). Tuples can be used in C#, but they are not idiomatic in C#:

// Assuming you have an operation like this 
let asyncDoWork () : Async<seq<DateTime * string>> = (...)

// Define a named type that explains what the date-string pair means
type Item(created:DateTime, name:string) =
  member x.Created = created
  member x.Name = name

// Create a simple wrapper that wraps values into 'Item' type
let asyncDoWorkItems () = 
  async { let! res = asyncDoWork()
          return seq { for (d, n) in res -> Item(d, n) } }

现在,揭露运行到C#,最好的做法是使用一类具有重载的静态方法。该方法开始操作一个任务,一个超载规定取消标记。这些C#的命名惯例是添加异步结束的名称(不与F#它增加了重叠异步来前):

Now, to expose the operation to C#, the best practice is to use a type with an overloaded static method. The method starts the operation as a task and one overload specifies cancellation token. The C# naming convention for these is to add Async to the end of the name (which doesn't overlap with F# which adds Async to the front):

type Work = 
  static member DoWorkAsync() =
    Async.StartAsTask(asyncDoWorkItems())
  static member DoWorkAsync(cancellationToken) =
    Async.StartAsTask(asyncDoWorkItems(), cancellationToken = cancellationToken)

您C#code就可以使用 Work.DoWorkAsync()并与通常的C#风格的任务的工作。它甚至会用等待关键字,这将是工作(可能)添加到C#5。

Your C# code can then use Work.DoWorkAsync() and work with the task in the usual C# style. It will even work with the await keyword that will be (probably) added to C# 5.

这篇关于从C#引用异步F#的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆