如何运行方法返回的任务?

问题描述 投票:0回答:1

尝试运行方法返回的任务并获取结果,

如何运行返回的Task并得到结果?

using System;
using System.Threading.Tasks;
                    
public class Program
{
    public static void Main()
    {
        var a = Test.DoWork();
    }
}

public class Test
{
    public static Task<string> DoWork()
    {
        var a = new Task<string>(() =>
        {
              return "Test Message";
        });

        return a;
    }   
}

运行任务

c#
1个回答
0
投票
using System;
using System.Threading.Tasks;

public class Program
{
    // Main method should be async to use await directly
    public static async Task Main()
    {
        // Await the result of the task returned by DoWork
        var result = await Test.DoWork();
        
        // Print the result
        Console.WriteLine(result);
    }
}

public class Test
{
    // Method returns a Task<string> and is marked as async
    public static async Task<string> DoWork()
    {
        // Simulate some asynchronous operation (e.g., delay)
        await Task.Delay(1000); // Simulating delay (like I/O operation)

        // Return the result asynchronously
        return "Test Message";
    }
}

Main 方法是异步的(async Task Main()),这是在控制台应用程序中运行异步代码的现代 C# 方法。

DoWork方法是异步的(async Task DoWork()),它使用await Task.Delay(1000)来模拟一些异步操作(例如I/O或Web请求)。 它在模拟延迟后返回一个字符串。

© www.soinside.com 2019 - 2024. All rights reserved.