任务<iresult>处理List <iresult>返回类型</iresult> </iresult>

时间:2014-10-22 19:56:28

标签: c# task-parallel-library async-await

我有以下代码行可供使用。问题是编译器一直抱怨这条线。请注意,表达式包含在它自己的异步方法中,因此使用await关键字,而被调用的方法也是异步调用的异步方法。 2个代码示例如下

var tresultString = await Task.FromResult(TestDataRepositoryAsync(testfilePath));

var tresultString = await Task.FromResult<List<IResultAd>>(TestDataRepositoryAsync(testfilePath));

当我在不使用Task.FromResult的情况下访问返回时,我得到类型

System.Threading.Tasks.Task`1[System.Collections.Generic.List`1[IResultAd]]

作为我的返回类型。

我得到的错误是

  1. System.Threading.Tasks.Task.FromResult<System.Collections.Generic.List<IResultAd>>(System.Collections.Generic.List<IResultAd>)的最佳重载方法匹配包含一些无效参数

  2. System.Threading.Tasks.Task.FromResult<System.Collections.Generic.List<IResultAd>>(System.Collections.Generic.List<IResultAd)的最佳重载方法匹配包含一些无效参数

  3. 参数1:无法转换为System.Threading.Tasks.Task<System.Collections.Generic.List<IResultAd>>' to 'System.Collections.Generic.List<IResultAd>

  4. 参数1:无法转换为'System.Threading.Tasks.Task<System.Collections.Generic.List<IResultAd>>' to 'System.Collections.Generic.List<IResultAd>'

  5. 以下是来自MSDN的示例

    // TASK<T> EXAMPLE
    async Task<int> TaskOfT_MethodAsync()
    {
        // The body of the method is expected to contain an awaited asynchronous 
        // call. 
        // Task.FromResult is a placeholder for actual work that returns a string. 
        var today = await Task.FromResult<string>(DateTime.Now.DayOfWeek.ToString());
    
        // The method then can process the result in some way. 
        int leisureHours;
        if (today.First() == 'S')
            leisureHours = 16;
        else
            leisureHours = 5;
    
        // Because the return statement specifies an operand of type int, the 
        // method must have a return type of Task<int>. 
        return leisureHours;
    }
    

    全部用于上面的相同代码行。如果您对代码示例的问题有任何帮助,我将不胜感激。提前谢谢。

    TestDataRepositoryAsync方法的签名:

    private async Task<List<IResultAd>> TestDataRepositoryAsync(String filePath)
    {
        using (var testfilestream =  File.OpenRead(filePath))
        {
            var getJsonStringFromFile = new StreamReader(testfilestream).ReadToEndAsync();
            var jsonString = await getJsonStringFromFil);
            List<IAdvertisement> result = JsonConvert.DeserializeObject<List<IResultAd>>(jsonString);
            return result;
        }
        return null; 
    }
    

    enter image description here

    enter image description here

    Task的Result属性让我可以访问我期望的结果。

    enter image description here

2 个答案:

答案 0 :(得分:1)

正如其他人所说,Task.FromResult的呼叫是不必要的。你的代码应该是:

var tresultString = await TestDataRepositoryAsync(testfilePath);

请注意,MSDN示例明确声明它使用Task.FromResult 作为异步工作的占位符,在您的情况下,TestDataRepositoryAsync

另一方面,当您使用异步文件流时,必须确保明确打开它们以进行异步访问:

using (var testfilestream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))

答案 1 :(得分:0)

在我的情况下,我必须访问返回的任务的Result属性。

enter image description here

相关问题