gpt4 book ai didi

c# - 在控制台应用程序中使用 Async 和 await

转载 作者:行者123 更新时间:2023-12-04 16:04:39 25 4
gpt4 key购买 nike

我有四种方法。

  • Main:只调用 preform 方法
  • 工作:显示“请等待用户”
  • 花时间:需要时间来执行的程序。
  • Preform:异步调用占用时间和工作方法。

  • 以下是我的代码:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    namespace AsyncObservation
    {
    class Program
    {
    static void Main(string[] args)
    {
    preform();
    }
    public static async Task Working()
    {
    Console.WriteLine("Please wait, the program is running");
    }
    public static async Task Takingtime()
    {
    Console.WriteLine("This Program started");
    Thread.Sleep(1000);
    Console.WriteLine("The Program finished");
    }
    public static async void preform()
    {
    Task timer = Takingtime();
    Task wait = Working();
    }
    }
    }

    最后:我需要显示
    This program started. 
    Please wait, the program is running
    The program ended.

    最佳答案

    我看到你的程序有几个问题。

  • 虽然 Preform既不是异步也不是事件处理程序,它不返回任务
  • 任务开始于 Preform在您完成 Preform 之前不会等待。因此,您永远不知道它们何时完成,也不知道结果如何(异常(exception)?)。您甚至可以在程序完成之前结束程序
  • 启动任务后,无法保证它何时运行。如果您等待任务,您只能确保语句已经执行。
  • 使用 async-await 是一种方法,可确保您的线程环顾四周以查看它是否可以做有用的事情,而不是在必须等待某事时无所事事地等待。 Thread.Sleep是忙碌的等待。如果您想环顾四周看看是否可以做其他事情,请使用 await Task.Delay(TimeSpan.FromSeconds(1))反而。

  • 在您的情况下,在您等待应该编写您的行的过程之前,您无法确定任何控制台行已被写入。如果您在等待第一个任务之前开始第二个任务,您不知道第一个任务已经进行了多远,因此您不能确定文本已经写入控制台。

    C# 7.1 introduced async Task Main() ,所以你可以用它代替传统的 void Main .它使您免于捕捉和解释 AggregateException这是由您开始使流程异步的任务引发的。

    如果您不想使用 async Main , 你当然可以使用 Task.Run调用异步函数:
    static void Main(string[] args)
    {
    try
    {
    var preformTask = Task.Run( () => Preform() );

    DoSomethingElse(); // if needed
    preformTask.Wait(); // wait for preformTask to finish

    Console.WriteLine("Task completed; press any key to finish");
    Console.ReadKey();
    }
    catch (Exception exc) // inclusive ggregateException if one of your Task fails
    {
    ProcessException(exc)
    }
    }

    static async Task preform()
    {
    // To be certain that the Console Line has been written: await
    await Takingtime();

    // if here, you are certain that the Line has been written,
    // or course you have lost parallel processing
    await Working();
    }

    为了完整性:其他功能
    public static async Task Working()
    {
    Console.WriteLine("Please wait, the program is running");

    // either return a completed Task, or await for it (there is a difference!
    await Task.CompletedTask;
    // or:
    return Task.CompletedTask; // do not declare async in this case
    }

    public static async Task Takingtime()
    {
    Console.WriteLine("This Program started");

    //Use Task.Delay instead of Sleep
    await Task.Delay(TimeSpan.FromSeconds(1); // improved readability
    Console.WriteLine("The Program finished");
    }

    因为等待 Preform你确定文本已经写好了。然而,你已经失去了一些平行性。

    如果您真的希望同时执行这些过程,则无法确定何时写入文本。如果这很重要,那么将应该首先运行的部件(写入控制台)与应该并行运行的部件(Task.Delay)分开
    static async Task preform()
    {
    // Do the things that should be done before parallel tasks are run
    await DoThisFirst();

    // start the Tasks that can work parallel: not sure what statements are executed first
    var taskA = DoTaskA();
    var taskB = DoTaskB();

    // if here, you are free to do something else
    // can't be sure about the status of taskA nor taskB
    DoSomethingElse();

    // if you want to do something after you know that the tasks have completed:
    // await the tasks here:
    await Task.When (new Task[] {taskA, taskB});

    // if here, you are certain that all parallel tasks have completed successfully
    // if desired fetch the return values of the Tasks:
    var returnValueA = taskA.Result;
    var returnValueB = taskB.Result;

    // do all async things of which you needed to be certain that both tasks finished
    // for example:
    await ProcessResults(returnValueA, returnValueB);
    }

    关于c# - 在控制台应用程序中使用 Async 和 await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51723066/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com