[英]Equivalent of Task.FromResult() from .NET 4.5 in .NET 4.0
I cant find information about retargeting my code from .NET 4.5 to 4.0. 我找不到有关将代码从.NET 4.5重定向到4.0的信息。 I have to install this application on Windows XP. 我必须在Windows XP上安装此应用程序。
my code in .NET 4.5 我在.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. 在.NET 4.0中,FromResult不存在。 Someone knows how it should looks in .NET 4.0?? 有人知道它在.NET 4.0中的外观吗?
You're returning the awaited result of a task, which is constructed on a result. 您将返回根据结果构造的任务的等待结果。 The solution is rather simple - drop the await
: 解决方案非常简单-删除await
:
return Sheet1;
The async
keyword in the method declaration will take care of wrapping it in a task. 方法声明中的async
关键字将负责将其包装在任务中。
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. 如果由于某种原因,你需要一个完成的任务手工包装已有的值,你可以使用TaskCompletionSource
-它比笨重有点Task.FromResult
,但只是有点。
I solved my problem with TaskCompletionSource
, here's my code: 我用TaskCompletionSource
解决了我的问题,这是我的代码:
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 ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.