C# Asynchronous IO: Is there a way of ensuring ordering of tasks?
I would like to use asynchronous io for socket communication with a distributed has开发者_如何转开发h server. Environment is C# 3.5, but could use 4.0 if necessary.
Suppose I issue the following asynchronous commands (in pseudocode):
socket.set_asynch("FOO","bar");
string rc = socket.get_asynch("FOO");
Since asynchronous io uses the system thread pool, the two commands may be run on two different threads. How can I ensure that rc equals "bar"? i.e. that the first command is issued before the second command is issued?
Thanks!
You could design your API around the Task<T> class (Task Parallel Library):
class DistributedHashTable
{
public Task SetAsync(string key, string value);
public Task<string> GetAsync(string key);
}
Both methods would use asynchronous IO to perform the respective operation, and set the returned Task<T> to completed when the operation has finished.
Then you could use your class synchronously like this:
var dht = new DistributedHashTable(...);
dht.SetAsync("FOO", "bar").Wait();
Console.WriteLine(dht.GetAsync("FOO").Result);
or asynchronously like this:
var dht = new DistributedHashTable(...);
dht.SetAsync("FOO", "bar")
.ContinueWith(t => dht.GetAsync("FOO"))
.Unwrap()
.ContinueWith(t => {
Console.WriteLine(t.Result);
});
or asynchronously using the Async CTP like this:
var dht = new DistributedHashTable(...);
await dht.SetAsync("FOO", "bar");
Console.WriteLine(await dht.GetAsync("FOO"));
精彩评论