2013-04-09 73 views
1

我有這樣的代碼這段代碼是否同步,因爲我希望它是?

public async Task<IEnumerable<WebResult>> SearchAsynch(string query) 
{ 
    if (query == null) 
    { 
    throw new ArgumentNullException("query cannot be null"); 
    } 

    DataServiceQuery<WebResult> webQuery = 
_bingContainer.Web(query, null, null, null, null, null, null, null); 

    return await Task.Factory.FromAsync 
       (webQuery.BeginExecute(null, null) 
       , asyncResult => webQuery.EndExecute(asyncResult) 
       ); 
} 

我把它叫做從而

public static void Main() 
{ 
    Search().Wait(); 
} 

private static async Task Search() 
{ 
    IWebSearcher webSearcher = new WebSearcher(); 
    for (var i = 0; i < 100; i++) 
    { 
     IEnumerable<WebResult> task = await webSearcher.SearchAsynch(i.ToString()); 

     var enumerator = task.GetEnumerator(); 
     enumerator.MoveNext(); 
     Console.WriteLine(enumerator.Current.Title); 
    } 
} 

我的問題是這樣。我希望這100個電話中的每一個都與SearchAsynch完全無關,因此第10個電話可能會在第9個電話之前返回並打印出結果。這似乎並沒有發生在這一刻。我做錯了什麼?

回答

2

做處理作爲完成任務的最簡單方法是定義做了處理一個單獨的方法,因爲這樣的:

public static async Task SearchAndPrintAsync(IWebSearcher webSearcher, string query) 
{ 
    var result = await webSearcher.SearchAsync(query); 
    using (var enumerator = result.GetEnumerator()) 
    { 
    if (enumerator.MoveNext()) 
     Console.WriteLine(enumerator.Current.Title); 
    else 
     Console.WriteLine("<none>"); 
    } 
} 

然後,你可以做併發async操作這樣:

private static async Task MainAsync() 
{ 
    IWebSearcher webSearcher = new WebSearcher(); 

    // Start all SearchAndPrint operations concurrently. 
    Task[] tasks = Enumerable.Range(0, 100) 
     .Select(i => SearchAndPrintAsync(webSearcher, i)) 
     .ToArray(); 

    // Wait for them all to complete. 
    await Task.WhenAll(tasks); 

    Console.WriteLine("Done"); 
} 

public static void Main() 
{ 
    MainAsync().Wait(); 
} 
+1

「SearchAndPrintAsync」方法違反了關注點的分離。它將數據訪問和演示混合在一起。 – Servy 2013-04-09 15:42:25

+2

我假設op只給了我們示例代碼,所以'Console.WriteLine'在邏輯上代表「做進一步處理」。 – 2013-04-09 15:45:49

+0

順便說一句,我認爲使用'First()'(或'FirstOrDefault()')比調用枚舉器更簡單。 (但我意識到你只是從問題中複製並修復了它。) – svick 2013-04-09 18:53:36

相關問題