【发布时间】:2011-04-15 13:17:22
【问题描述】:
我阅读了几篇 F# 教程,并且注意到与 C# 相比,在 F# 中执行异步和并行编程是多么容易。因此,我正在尝试编写一个 F# 库,该库将从 C# 调用,并将 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()
【问题讨论】:
标签: c# asynchronous f# callback workflow