日期:2014-05-17  浏览次数:21140 次

async怎么实现非异步接口?
Win8的Metro程序。有一个类,要实现一个接口,里面有一个int GetUserChoice()方法。
在UI界面中,需要弹出一个对话框,让用户选择,得到结果。但是对话框显示需要等待,不能返回int。这个功能需要怎么实现?

相关代码:

// 不能返回int public int GetUserChoice()
public async Task<int> GetUserChoice //但是这样又不能实现接口
{
    MessageDialog d = new MessageDialog("请选择:");
    d.Commands.Add(new UICommand("类型1", null, 1));
    d.Commands.Add(new UICommand("类型2", null, 2));
    d.Commands.Add(new UICommand("类型3", null, 3));
    IUICommand cmd = await d.ShowAsync();
    int choice = Convert.ToInt32(cmd.Id);
    return choice;
}

------解决方案--------------------
public int GetUserChoice //但是这样又不能实现接口
{
    MessageDialog d = new MessageDialog("请选择:");
    d.Commands.Add(new UICommand("类型1", null, 1));
    d.Commands.Add(new UICommand("类型2", null, 2));
    d.Commands.Add(new UICommand("类型3", null, 3));
    var task = d.ShowAsync();
    var result = task.WaitAndUnwrapException().Result;
    int choice = Convert.ToInt32(result.Id);
    return choice;
}
------解决方案--------------------
http://stackoverflow.com/questions/12402681/is-it-possible-to-call-an-awaitable-method-in-a-non-async-method