简体   繁体   中英

Convert Long to Task<long>

I am just learning about Async programming from a book and hehe! their example doesn't work.

Author (Adam Freeman in WebAPI2 book, Chapter 3, Page 47! ) wants to explain a technique that when we have a series of sync statements and we want to execute them Async . He says

this is done by creating a starting a task that wrap around the statements that we need to execute and return the Task as the result from the method.

Then he says look at this example. Well Surprise! it doesn't even work because it can't convert from long to Task<long>

How am I supposed to fix this code?

public interface ICustomController
{
    Task<long> GetPageSize(CancellationToken cancellationToken);
}
public Task<long> GetPageSize(CancellationToken cancellationToken)
{
    WebClient wb = new WebClient();
    Stopwatch sw = Stopwatch.StartNew();

    List<long> results = new List<long>();

    for(int i=0; i<10; i++)
    {
        if (!cancellationToken.IsCancellationRequested)
        {
            Debug.WriteLine("Making Request {0} ", i);
            results.Add(wb.DownloadData(TargetUrl).LongLength);

        }
        else
        {
            Debug.WriteLine("Cancelled...");
            return 0;
        }
    }

    Debug.WriteLine("Elapsed ms: {0} ", sw.ElapsedMilliseconds);

    return (long)results.Average();
}

Note that he has intentionally removed the aysnc and await from the method so he can explain this technique..but he has forgot to actually fix his code.

return Task.FromResult((long)results.Average());

这是您从非异步函数返回等待结果的方法。

I would assume he wanted to use Task.Run() to load the work of to a threadpool thread. You can use it like

public Task<long> GetPageSize(CancellationToken cancellationToken))
{
    return Task.Run(() => 
    {
         // body of the original methode
    });
}

And the caller than can just await the returned Task -object.

Read more about Task.Run() here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM