Windows Store Apps and F#

2019-03-29 17:22发布

问题:

I am trying to create a portable library using F# to use with Windows Store apps. I created one fs file with one class:

module FunctionalRT

open System.Net
open System.IO

type WebHelper =

    static member DownloadStringAsync (url:string) = async {
        let req = HttpWebRequest.Create(url)
        use! resp = req.AsyncGetResponse()
        use stream = resp.GetResponseStream()
        let reader = new StreamReader(stream) 
        let s = reader.ReadToEnd()
        return s
    }

I referenced this library in my Windows Store app with no problems. But the problem is, I cannot access the FunctionalRT module neither the WebHelper class. When I write using FunctionalRT or try to use FunctionalRT.WebHelper.FunctionalRT, the compiler complains it does not know it. What may be the problem?

EDIT: After a few buidls and cleans I get

The type 'Microsoft.FSharp.Control.FSharpAsync`1<T0>' is defined in an assembly that is not referenced. You must add a reference to assembly 'FSharp.Core, Version=2.3.5.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.  C:\Users\Igor\Documents\Visual Studio 2012\Projects\App3\App3\GroupedItemsPage.xaml.cs  46  13  App3

EDIT:

Adding a reference to C:\Program Files (x86)\MSBuild\..\Reference Assemblies\Microsoft\FSharp\3.0\Runtime\.NETPortable\FSharp.Core.dll solved the above error message, but there is another one

Cannot await 'Microsoft.FSharp.Control.FSharpAsync<string>'

回答1:

You have to reference this library in your Windows Store app to make it work:

C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\3.0\Runtime.NETPortable\FSharp.Core.dll

And regarding that FSharpAsync class, see this thread:
Referencing Asynchronous F# datatype from C#

You could use static method of the FSharpAsync type for awaiting the returned object.



回答2:

If you're calling this code from C#, it would probably integrate better like this:

static member DownloadStringAsync (url:string) = async {
    let req = HttpWebRequest.Create(url)
    use! resp = req.AsyncGetResponse()
    use stream = resp.GetResponseStream()
    let reader = new StreamReader(stream) 
    let s = reader.ReadToEnd()
    return s
} |> Async.StartAsTask

Then your C# project will not need to reference FSharp.Core, and you can use the standard C# await keyword just as if you were calling C# async code.