Calling an async method from a non-async method

淺唱寂寞╮ 提交于 2019-12-04 06:57:39

The tasks you returned haven't started yet (i.e., they're "cold" tasks); try replacing the PrepareAwaitable code with the following:

static Task<string> PrepareAwaitable(int x)
{
    return Task.Factory.StartNew<string>(() =>
    {
        return "Howdy " + x.ToString();
    });
}

First, read the Task-Based Asynchronous Pattern document. It's under My Documents\Microsoft Visual Studio Async CTP\Documentation. This document describes how to design APIs naturally consumable by await.

Secondly, realize that there are several aspects of the Task class and related APIs that no longer really apply in the new asynchronous world. Task was originally written as the core of TPL. It turned out to be a good fit for asynchronous programming, so Microsoft used it instead of creating a new "Promise" class. But a number of methods are holdovers, used by TPL but not needed for async programming.

To answer the titular question, mixing synchronous and asynchronous code is not quite straightforward with the current async CTP. I've written a library that includes a Task.WaitAndUnwrapException extension method, which makes it easy to call async code from sync code. You may also be interested in my AsyncContext class, which makes the "press any key" prompt unnecessary.

It's really not clear what you're trying to achieve, because there's nothing asynchronous going on. For example, this will compile and run, but I don't know whether it's what you want:

using System;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        DoSomething();

        Console.WriteLine("Press any key to quit.");
        Console.ReadKey();
    }

    static async void DoSomething()
    {
        Console.WriteLine("Starting DoSomething ...");

        var x = await PrepareAwaitable(1);

        Console.WriteLine("::" + x);

        var y = await PrepareAwaitable(2);

        Console.WriteLine("::" + y);
    }

    static async Task<string> PrepareAwaitable(int x)
    {
        return "Howdy " + x;
    }
}

Note that this gives a warning for PrepareAwaitable because there's nothing asynchronous in it; no "await" expressions. The whole program executes synchronously. Another alternative implementation of PrepareAwaitable:

static Task<string> PrepareAwaitable(int x)
{
    return TaskEx.Run(() => "Howdy " + x);
}

Is that more like what you were after?

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