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

时间:2011-04-15 13:17:22

标签: c# asynchronous f# callback workflow

我已经阅读了几篇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()

1 个答案:

答案 0 :(得分: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() }

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

如果您想使用F#来获得异步工作流的好处,那么最好的选择是在F#中实现操作,然后使用Async.StartAsTask将它们公开给C#(这会为您提供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))

如果您不想使用F#(至少用于执行异步计算),那么异步工作流程将无法帮助您。您可以使用TaskBackgroundWorker或其他C#技术实现类似的功能(但是如果不阻塞线程,您将无法轻松运行操作)。