2010-12-06 37 views
1

我想使用異步io與分佈式哈希服務器進行套接字通信。環境是C#3.5,但如果需要可以使用4.0。C#異步IO:有沒有確保任務排序的方法?

假設我發出以下異步命令(在僞代碼):

socket.set_asynch("FOO","bar"); 
string rc = socket.get_asynch("FOO"); 

由於異步IO使用系統線程池,這兩個命令可以在兩個 不同的線程中運行。我如何確保rc等於「bar」?即在發出第二個命令之前發出第一個命令 ?

謝謝!

+8

使用同步IO ? – ChaosPandion 2010-12-06 00:12:48

+1

@ChaosPandion:我喜歡,但它是真的。 – 2010-12-06 00:13:55

回答

6

你可以設計圍繞Task<T> class(任務並行庫)的API:

class DistributedHashTable 
{ 
    public Task SetAsync(string key, string value); 

    public Task<string> GetAsync(string key); 
} 

這兩種方法都將使用異步IO來執行相應的操作,並返回任務<牛逼>設置操作完成時已完成。

然後你可以同步使用你的類是這樣的:

var dht = new DistributedHashTable(...); 

dht.SetAsync("FOO", "bar").Wait(); 

Console.WriteLine(dht.GetAsync("FOO").Result); 

或異步像這樣:

var dht = new DistributedHashTable(...); 

dht.SetAsync("FOO", "bar") 
    .ContinueWith(t => dht.GetAsync("FOO")) 
    .Unwrap() 
    .ContinueWith(t => { 
          Console.WriteLine(t.Result); 
         }); 

或異步使用Async CTP這樣的:

var dht = new DistributedHashTable(...); 

await dht.SetAsync("FOO", "bar"); 

Console.WriteLine(await dht.GetAsync("FOO"));