2010-12-06 50 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"));