4

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??

P10trek
  • 167
  • 4
  • 15
  • Add [`Microsoft Async`](https://www.nuget.org/packages/Microsoft.Bcl.Async/) to project packages. – raidensan Nov 04 '16 at 12:36
  • https://msdn.microsoft.com/en-us/library/hh194922(v=vs.110).aspx check this and also in .Net 4 you can't use async/await from what I remember – mybirthname Nov 04 '16 at 12:39
  • Still same problem. – P10trek Nov 04 '16 at 12:39
  • The code for that method is just `return new Task(result);`. https://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs,11a386e7d7cae64a So, I'd think you can just do `return Sheet1;` there regardless of which version of .Net. – juharr Nov 04 '16 at 12:41

2 Answers2

3

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 ;
        }
P10trek
  • 167
  • 4
  • 15
2

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.

Luaan
  • 62,244
  • 7
  • 97
  • 116