如何从c#调用和处理异步f#工作流

本文关键字:处理 异步 工作流 调用 | 更新日期: 2023-09-27 17:50:12

我读了一些f#教程,我注意到与c#相比,在f#中执行异步和并行编程是多么容易。因此,我正在尝试编写一个f#库,它将从c#中调用,并将c#函数(委托)作为参数并异步运行。

到目前为止,我已经成功地传递了这个函数(我甚至可以取消),但我错过的是如何实现回调到c#,这将在异步操作完成后立即执行。(例如函数AsynchronousTaskCompleted?)此外,我想知道我是否可以将(例如进度%)从那时的函数异步任务发布回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()

如何从c#调用和处理异步f#工作流

要获得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#技术实现类似的事情(但您将失去在不阻塞线程的情况下轻松运行操作的能力)。