首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

async如何实现非异步接口

2013-07-09 
async怎么实现非异步接口?Win8的Metro程序。有一个类,要实现一个接口,里面有一个int GetUserChoice()方法。

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

热点排行