0

我正在上 WinRT IAsyncOperation、async、await 的速成课程。我正在尝试用 IAsyncOperation 包装任务,但未能想出一种简单的方法来进行强制转换。

public interface IInfo{}
public class InfoList : IInfo{}

public class Parser {
    private async Task<InfoList> ParseList() {
        var returnList = new InfoList();

        HttpClient client = new HttpClient();
        Task<string> htmlTask = client.GetStringAsync("http://stackoverflow.com");

        string html = await htmlTask;
        // parsing logic...
        return returnList;
    }

    public IAsyncOperation<IInfo> Parse()
    {
        return AsyncInfo.Run(_ =>
            Task.Run<IInfo>(async () =>
            {
                var returnList = await ParseList();
                return returnList;
            })
        );
        // I have tried following but causes InvalidCastException
        //return (IAsyncOperation<IInfo>)ParseList().AsAsyncOperation<InfoList>();
    }
}
4

2 回答 2

3
public IAsyncOperation<IInfo> Parse()
{
    return AsyncInfo.Run(async _ => (IInfo) await ParseList());
}

或者

public IAsyncOperation<IInfo> Parse()
{
    return AsyncInfo.Run(_ => ParseList().ContinueWith(t => (IInfo)t.Result));
}
于 2012-12-11T19:40:44.990 回答
2

类型不是协变的IAsyncOperation<>,这意味着您不能将 an 强制IAsyncOperation<InfoList>转换为IAsyncOperation<IInfo>.

尝试让您的ParseList方法返回 a Task<IInfo>

于 2012-12-10T17:36:32.177 回答