Equivalent of Task.FromResult() from .NET 4.5 in .NET 4.0

心不动则不痛 提交于 2019-12-06 12:07:38

问题


I cant find information about retargeting my code from .NET 4.5 to 4.0. I have to install this application on Windows XP.

my code in .NET 4.5

public async Task <IXLWorksheet> ImportFile(string fileToImport)
{
    ...
    return await Task.FromResult<IXLWorksheet>(Sheet1)
}

In .NET 4.0 method FromResult does not exist. Someone knows how it should looks in .NET 4.0??


回答1:


You're returning the awaited result of a task, which is constructed on a result. The solution is rather simple - drop the await:

return Sheet1;

The async keyword in the method declaration will take care of wrapping it in a task.

If, for some reason, you need to manually wrap an existing value in a completed task, you can use TaskCompletionSource - it's a bit clunkier than Task.FromResult, but just a bit.




回答2:


I solved my problem with TaskCompletionSource, here's my code:

 public async Task <IXLWorksheet> ImportFile(string fileToImport)
        {
         ...
                TaskCompletionSource<IXLWorksheet> tcs1 = new TaskCompletionSource<IXLWorksheet>();
                Task<IXLWorksheet> t1 = tcs1.Task;
                tcs1.SetResult(tempFile.Worksheet(1));
                return await t1 ;
        }


来源:https://stackoverflow.com/questions/40422779/equivalent-of-task-fromresult-from-net-4-5-in-net-4-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!