代码未在嵌套异步方法中执行

时间:2012-09-23 21:44:26

标签: c# microsoft-metro async-await

我坚持为什么我无法从异步方法调用返回一个值。

我没有收到任何错误。

ReadAsync 方法无法完全执行,导致我无法单步执行剩余的代码行。

请帮忙。 你是我唯一的希望......

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        QuoteParameters quote = e.Parameter as QuoteParameters;
        Debug.Assert(quote != null);

        var task = _viewModel.GenerateQuote(quote);
        string address = task.Result;
        webView.Source = new Uri(address);
    }

    public async Task<string> GenerateQuote(QuoteParameters quote)
    {
        var documentedQuote = quote.Convert();
        var task = QuoteGenerator.Execute(documentedQuote);

        string filePath = await task; **// EXECUTION STOPS AT THIS POINT!**

        return filePath;
    }


    public async static Task<string> Execute(QuoteParameters quote)
    {
        string html = string.Empty;

        foreach (var service in quote.Services)
        {
            var quoteTemplateTask = IO.ReadAsync(TEMPLATES_DIRECTORY, DOC_TEMPLATE);
            string quoteTemplate = await quoteTemplateTask;

            var serviceTemplateTask = IO.ReadAsync(TEMPLATES_DIRECTORY, SERVICE_TEMPLATE);
            string serviceTemplate = await serviceTemplateTask;

            var serviceAppliedTemplate = Apply(quoteTemplate, quote.Services, serviceTemplate);

            var materialTemplate = IO.ReadAsync(TEMPLATES_DIRECTORY, MATERIAL_TEMPLATE);
            html = Apply(serviceAppliedTemplate, service.Materials, await materialTemplate);
        }

        return await SaveAsync(html);
    }

    public static async Task<string> ReadAsync(string directoryExtension, string fileName)
    {
        string filePath = BuildPath(directoryExtension, fileName);
        string directoryName = Path.GetDirectoryName(filePath);

        StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(directoryName);
        StorageFile storageFile = await storageFolder.GetFileAsync(fileName); **// EXECUTION STOPS HERE**

        IRandomAccessStream randomAccessStream = await storageFile.OpenAsync(FileAccessMode.Read);
        IInputStream inputstream = randomAccessStream.GetInputStreamAt(0);
        DataReader dataReader = new DataReader(inputstream);

        var numberOfBytesLoaded = dataReader.LoadAsync((uint)randomAccessStream.Size);

        return dataReader.ReadString(await numberOfBytesLoaded);
    }

1 个答案:

答案 0 :(得分:1)

您的问题出在OnNavigatedTo。具体来说,您对Task.Result的调用导致死锁。 Don't block on async code

您可以试试这个,但我不确定OnNavigatedTo的工作情况async是多少(该方法会在设置webView.Source之前返回,这可能不是您想要的) :

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    QuoteParameters quote = e.Parameter as QuoteParameters;
    Debug.Assert(quote != null);

    var task = _viewModel.GenerateQuote(quote);
    string address = await task;
    webView.Source = new Uri(address);
}