【问题标题】:Can I use async/await inline in C# [duplicate]我可以在 C# 中使用 async/await inline [重复]
【发布时间】:2018-08-18 09:59:06
【问题描述】:

我有代码,可以异步运行一些块。如何在不创建 LongTask() 和 LongOperationAsync() 函数的情况下使 LongOperation() 以“内联”方式(直接从 Main 方法)异步运行?

class Program
{
    static void Main(string[] args)
    {
        LongOperationAsync();
        Console.WriteLine("Main thread finished.");
        Console.ReadKey();     
    }

    static void LongOperation()
    {
        Thread.Sleep(3000);
        Console.WriteLine("Work completed");
    }

    static Task LongTask()
    {
        return Task.Run(() => LongOperation());
    }

    static async void LongOperationAsync()
    {
        await LongTask();
        Console.WriteLine("Callback triggered");
    }

}

更新

我希望我做对了。我的意思是,我想让任何现有函数异步并在执行后添加一些操作而不添加任何新函数。似乎下面的解决方案正在运行。

class Program
{

    static void Main(string[] args)
    {

        ((Action)(async () =>
        {
            await Task.Run(() => LongOperation());
            Console.WriteLine("Then callback triggered");
        }))();

        Console.WriteLine("Main thread finished first.");


        Console.ReadKey();

    }

    static void LongOperation()
    {
        Thread.Sleep(3000);
        Console.WriteLine("Work completed");
    }
}

【问题讨论】:

  • 你能看看我的UPD,看看它是对还是错?我认为您标记为重复的问题中的答案并不完全相同。

标签: c#


【解决方案1】:

您可以使用 GetAwaiter().GetResult()

static void Main(string[] args)
{
    Console.WriteLine(v);
    LongOperationAsync().GetAwaiter().GetResult();
    Console.WriteLine("Main thread finished.");
    Console.ReadKey();     
}

this SO question了解更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2021-09-26
    相关资源
    最近更新 更多