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

|| 我读过一些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()
    
已邀请:
为了获得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() }
您只能在
async
块内使用异步操作,它依赖于F#编译器处理
do!
let!
的方式。对于以顺序方式(例如,在C#或F#中的
async
块之外)编写的代码,没有(简便)的方法来获得真正的非阻塞执行。 如果要使用F#来获得异步工作流的好处,那么最好的选择是在F#中实现这些操作,然后使用
Async.StartAsTask
将它们公开给C#(这使C#可以轻松使用
Task<T>
)。像这样:
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))
如果您不想使用F#(至少用于实现异步计算),那么异步工作流将无济于事。您可以使用
Task
BackgroundWorker
或其他C#技术来实现类似的事情(但是您将失去在不阻塞线程的情况下轻松运行操作的能力)。     

要回复问题请先登录注册