Silverlight等待异步调用

本文关键字:调用 异步 等待 Silverlight | 更新日期: 2023-09-27 18:16:12

我有一个silverlight应用程序,当它启动时,它需要读取一个webservice返回的配置文件。

那么,在我的主页中,我想要这样做:

public MainPage()
{
    InitializeComponent();
    Config cfg = new Config();
    XDocument config = cfg.getConfig();
    //doing stuff with config here
    ...
}

config的构造函数调用readConfigAsnc,我有一个readcompleted返回xdocument的方法。我想在MainPage()中继续执行之前调用readConfigCompleted。做这件事的最好方法是什么?

Silverlight等待异步调用

最好的方法是把它分成两个方法。传递一个函数作为getConfig的参数,如下所示:

cfg.getConfig( fcnToCall );

之后,在你的代码中,

void fcnToCall( XDocument config )
{
    //Do stuff with config here...
}

如果你想保留你的局部变量,另一个选择是使用lambda表达式:

Config cfg = new Config();
cfg.Callback += new Action<XDocument> action = s => 
        {
            XDocument cfg = s as XDocument;
            //Do stuff with config here...
        };
cfg.getConfig();

为什么不把方法分开呢?而不是让所有这些发生在MainPage()中,让'Do Stuff'发生在GetConfigCompleted事件