WCF (C#), calling an Async method. help!
I'm stumped with this and would appreciate any help at all!
I'm calling the Amazon api using WCF and the Visual Studio generated -asynch- methods.
There's a WPF page
, with a button on. Press the button and it calls the search method in another class. (see code below)
In this other searcher class, I add the method AmazonItemSearchCompleted
to handle the ItemSearchCompleted
event. Then I call the asynch search function from the generated wcf code.
Client.ItemSearchCompleted += AmazonItemSearchCompleted;
Client.ItemSearchAsync(itemSearch);
This all seems to work fine. But the AmazonItemSearchCompleted
method only seems to get hit after all the code in the calling form ends, ie. when I'm stepping though (no matter how long I wait for the service to respond), it gets hit at the final bracket after searchAmazon
(). But by this time, it's too late to use the result of the request!!
private void button1_Click(object sender, RoutedEventArgs e)
{
searchAmazon();
} // <----- AmazonItemSearchCompleted get's hit here
private void searchAmazon()
{
var AzSearch = new AmazonSearch();
var ISBNS = new List<string>();
ISBNS.Add("043902351开发者_运维知识库3");
//ISBNS.Add("9780071374323");
AzSearch.GetBookNameFromISBN(ISBNS[0]);
}
Maybe I'm missing something here, but I have no idea why the event seems to fire late?
Should I abandon the asynch methods and use the synchronous ones with a background worker?? (maybe more straightforward?)
Thanks for any help or pointers you can offer!
That's the whole point of async methods. You fire them and the code returns immediately to avoid blocking the UI until the service responds. You use the result only in the success callback (AmazonItemSearchCompleted
). In the case of a WPF application if you use async methods you should be aware that the success callback could be invoked on a thread which is different than the main GUI thread and in which you should not update the controls. You need to use the Dispatcher object.
精彩评论