简体   繁体   中英

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("0439023513");
        //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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM