Consumption F # Async from C #

Suppose I have the following code:

namespace Library1

open System.Threading.Tasks
open System.Threading
open System.Runtime.Remoting.Messaging
open System

type public Class1() =

    let printThread (message) = 
        printfn "%s %A" message Thread.CurrentThread.ManagedThreadId

    let bar = 
        printThread ("first bar")
        async { 
            printThread ("first async")
            do! Async.Sleep(1000)
            printThread "last async"
        }

    member this.X() =  bar

X #. , X Async < T. F #. . Async.StartAsTask , . , , Async.StartImmediate. , . , , . , Async.StartImmediate, . ?

+4
3

, ( , int):

type public Class1() = 
    let printThread (message) = printfn "%s %A" message Thread.CurrentThread.ManagedThreadId

    let bar = 
        printThread ("first bar")
        async { 
            printThread ("first async")
            do! Async.Sleep(1000)
            printThread "last async"
            return 1232
         }

    member this.convertToTask<'T> (asyn : Async<'T>) = 
       let tcs1 = new TaskCompletionSource<'T>()
       let t1 = tcs1.Task
       Async.StartWithContinuations
        (
          asyn 
          , (fun (k) -> tcs1.SetResult(k)), (fun exn -> tcs1.SetException(exn)), fun exn -> ())
        t1

    member this.X() : Task<int> =  (bar |> this.convertToTask)
+2

Async<'T> Task<'T> Async.StartAsTask<'T>.

, # F # , Task<'T>. , F # AsyncFoo # FooAsync.

, - :

type public Class1() =

    let printThread (message) = 
        printfn "%s %A" message Thread.CurrentThread.ManagedThreadId

    let bar = 
        printThread ("first bar")
        async { 
            printThread ("first async")
            do! Async.Sleep(1000)
            printThread "last async"
        }

    member this.AsyncFoo() =  bar

    /// Expose C#-friendly asynchronous method that returns Task
    member this.FooAsync() = Async.StartAsTask(bar)
    /// Expose C#-friendly asynchronous method that returns Task
    /// and takes cancellation token to support cancellation...
    member this.FooAsync(cancellationToken) = 
      Async.StartAsTask(bar, ?cancellationToken=cancellationToken)
+2

X ?

member this.X() = 
    let t = new Task(fun () -> bar |> Async.StartImmediate)
    t.RunSynchronously()
    t

, , . , #:

Console.WriteLine("X " + Thread.CurrentThread.ManagedThreadId);
var c = new Class1();            
c.X().Wait();

Thread.Sleep(2000);

:

X 7
first bar 7
first async 7
last async 11

, #, X Task X().

0

Source: https://habr.com/ru/post/1534425/


All Articles