你所想,使並行程序,有一個IO通話爲主要方面,所以它能夠更好地使用使用TaskCompletionSource
異步編程,因爲Webclient
的DownloadAsync
方法返回一個void
。以下是ReadData
修改後的版本:通過async
方法,它可以await
,直到所有的下載調用返回
public Task<string> ReadData(int i)
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
var client = new WebClient();
string uriString = @"http://someforum.com/page?id=" + i;
client.DownloadStringCompleted += (sender,args) =>
{
tcs.TrySetCanceled();
tcs.TrySetException(args.Error);
tcs.TrySetResult(args.Result);
};
client.DownloadStringAsync(new Uri(uriString));
return tcs.Task;
}
調用READDATA異步
你可以最好做到這一點。另外,作爲其多個Async
通話中,以便最好設置限制i
,就像你不能檢查每個下載和返回的值同步的版本,所有來電都在這種情況下
public async Task<LinkedList<string>> ReadDataAsync()
{
var docs = new LinkedList<string>();
List<Task<string>> taskList = new List<Task<string>>();
for (int i = 0; ; ++i) // Set a limit to i, since you are not running synchronously, so you cannot keep checking which value yields null as result
{
int localId = i;
taskList.Add(ReadData(localId));
}
await Task.WhenAll(taskList);
// Do Link List processing, if the Task is not cancelled and doesn't have an error, then result can be accessed
}
「WebClient」的實例成員不是線程安全的。 –
我編輯了代碼。 – user1681317
'LinkedList'也不是線程安全的。 ;) –