C# 5.0 提供了 Async 關鍵字,用來做非同步的功能。當然在 F# 也會有同樣的功能,而且個人認為寫法比 C# 稍微簡潔一些。
下列 F# 程式碼,宣告了一個 async 區塊,之後再呼叫 Async 類別的 StartAsTask 方法。
namespace FSharpLibrary
type AsyncTestClass1() =
member this.AsyncTest() =
let method1 =
async {
do! Async.Sleep(3000)
return "Test Value"
}
//method1 |> Async.StartAsTask
Async.StartAsTask method1這樣的寫法,程式碼不但精簡,而且也容易理解。
接下來的程式碼是用 C# 的 WinForm 專案來做示範,使用上並沒有不同。
private async void button1_Click(object sender, EventArgs e)
{
string strResult = string.Empty;
this.label1.Text = "waiting....";
AsyncTestClass1 c = new AsyncTestClass1();
strResult = await c.AsyncTest();
this.label1.Text = strResult;
}文章標籤
全站熱搜
