如何从C#调用和处理异步F#工作流

Ioa*_*nis 2 c# workflow f# asynchronous callback

我已经阅读了几篇F#教程,我注意到与C#相比,在F#中执行异步和并行编程是多么容易.因此,我正在尝试编写一个将从C#调用的F#库,并将C#函数(委托)作为参数并以异步方式运行.

到目前为止我已经设法传递了这个函数(我甚至可以取消)但是我想念的是如何实现回调到C#的回调,一旦异步操作完成就会执行它.(例如函数AsynchronousTaskCompleted?).另外我想知道我是否可以从函数AsynchronousTask发布(例如Progress%)回F#.

有人可以帮帮我吗?

这是我到目前为止编写的代码(我不熟悉F#所以以下代码可能是错误的或执行不当).

//C# Code Implementation (How I make the calls/handling)
        //Action definition is: public delegate void Action();
        Action action = new Action(AsynchronousTask);
        Action cancelAction = new Action(AsynchronousTaskCancelled);
        myAsyncUtility.StartTask2(action, cancelAction);
        Debug.WriteLine("0. The task is in progress and current thread is not blocked");
        ......
        private void AsynchronousTask()
        {
            //Perform a time-consuming task
            Debug.WriteLine("1. Asynchronous task has started.");
            System.Threading.Thread.Sleep(7000);
            //Post progress back to F# progress window?
            System.Threading.Thread.Sleep(2000);
        }        
        private void AsynchronousTaskCompleted(IAsyncResult asyncResult)
        {           
            Debug.WriteLine("2. The Asynchronous task has been completed - Event Raised");
        }
        private void AsynchronousTaskCancelled()
        {
            Debug.WriteLine("3. The Asynchronous task has been cancelled - Event Raised");
        }

//F# Code Implementation
  member x.StartTask2(action:Action, cancelAction:Action) = 
        async {
            do! Async.FromBeginEnd(action.BeginInvoke, action.EndInvoke, cancelAction.Invoke)
            }|> Async.StartImmediate
        do printfn "This code should run before the asynchronous operation is completed"    
        let progressWindow = new TaskProgressWindow()
        progressWindow.Run() //This class(type in F#) shows a dialog with a cancel button
        //When the cancel button is pressed I call Async.CancelDefaultToken()

  member x.Cancel() =
        Async.CancelDefaultToken()
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 8

要获得F#异步工作流的好处,您必须在F#中实际编写异步计算.您尝试编写的代码不起作用(即它可能会运行,但不会有用).

当您在F#中编写异步计算时,可以使用let!和进行异步调用do!.这允许您使用其他原始非阻塞计算.例如,您可以使用Async.Sleep而不是Thread.Sleep.

// This is a synchronous call that will block thread for 1 sec
async { do Thread.Sleep(1000) 
        someMoreStuff() }

// This is an asynchronous call that will not block threads - it will create 
// a timer and when the timer elapses, it will call 'someMoreStuff' 
async { do! Async.Sleep(1000)
        someMoreStuff() }
Run Code Online (Sandbox Code Playgroud)

您只能在async块内部使用异步操作,它依赖于F#编译器处理的方式do!let!.对于以顺序方式编写的代码(例如,在C#中或async在F#中的块外部),没有(简单)方法来获得真正的非阻塞执行.

如果您想使用F#来获得异步工作流的好处,那么最好的选择是在F#中实现操作,然后将它们暴露给C#使用Async.StartAsTask(这使您Task<T>可以轻松使用C#).像这样的东西:

let someFunction(n) = async {
  do! Async.Sleep(n)
  Console.WriteLine("working")
  do! Async.Sleep(n)
  Console.WriteLine("done") 
  return 10 }

type AsyncStuff() = 
  member x.Foo(n) = someFunction(n) |> Async.StartAsTask

// In C#, you can write:
var as = new AsyncStuff()
as.Foo(1000).ContinueWith(op =>
    // 'Value' will throw if there was an exception
    Console.WriteLine(op.Value))
Run Code Online (Sandbox Code Playgroud)

如果您不想使用F#(至少用于实现异步计算),那么异步工作流程将无法帮助您.您可以实现使用类似的事情Task,BackgroundWorker或其他C#技术(但你会失去在不阻塞线程轻松运行操作的能力).