加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#异步和等待不起作用

发布时间:2020-12-15 23:47:36 所属栏目:百科 来源:网络整理
导读:为什么以下异步并等待不起作用?我试图了解这是想了解我的代码有什么问题. class Program{ static void Main(string[] args) { callCount(); } static void count() { for (int i = 0; i 5; i++) { System.Threading.Thread.Sleep(2000); Console.WriteLine(
为什么以下异步并等待不起作用?我试图了解这是想了解我的代码有什么问题.

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

        callCount();

    }

    static void count()
    {
        for (int i = 0; i < 5; i++)
        {
            System.Threading.Thread.Sleep(2000);
            Console.WriteLine("count loop: " + i);
        }
    }

    static async void callCount()
    {
        Task task = new Task(count);
        task.Start();
        for (int i = 0; i < 3; i++)
        {
            System.Threading.Thread.Sleep(4000);
            Console.WriteLine("Writing from callCount loop: " + i);
        }
        Console.WriteLine("just before await");
        await task;
        Console.WriteLine("callCount completed");
    }
}

程序将启动count()方法,但在没有完成的情况下退出.随着等待任务;语句我希望它在退出之前等待完成count()方法的所有循环(0,1,2,3,4).我只得到“计数循环:0”.但是它经历了所有的callCount().它就像等待任务一样没有做任何事情.我希望count()和callCount()都异步运行并在完成时返回main.

解决方法

当您执行异步方法时,它会同步开始运行,直到它到达await语句,然后其余的代码异步执行,并且执行返回给调用者.

在你的代码中,callCount()开始同步运行到await任务,然后回到Main()方法,由于你没有等待方法完成,程序结束而没有方法count()可以完成.

通过将返回类型更改为Task,并在Main()方法中调用Wait(),可以看到所需的行为.

static void Main(string[] args)
{
    callCount().Wait();
}

static void count()
{
    for (int i = 0; i < 5; i++)
    {
        System.Threading.Thread.Sleep(2000);
        Console.WriteLine("count loop: " + i);
    }
}

static async Task callCount()
{
    Task task = new Task(count);
    task.Start();
    for (int i = 0; i < 3; i++)
    {
        System.Threading.Thread.Sleep(1000);
        Console.WriteLine("Writing from callCount loop: " + i);
    }
    Console.WriteLine("just before await");
    await task;
    Console.WriteLine("callCount completed");
}

编辑:
这是您的代码执行方式:

(为了更好地理解,允许更改CallCount()将类型返回到Task)

>程序以Main()方法开头.
>调用CallCount()方法.
>创建任务,所有这些都在同一个线程中.
>然后任务开始.此时,创建一个并行运行Count()方法的新线程.
>在CallCount()中继续执行,执行循环并打印“就在等待之前”.
>然后等待任务;到达了.这是async-await模式发挥作用的时候. await不像Wait(),它在任务完成之前不阻塞当前线程,但是将执行控制返回到Main()方法以及CallCount()中的所有剩余指令(在本例中只是Console.WriteLine(“ callCount完成“);)将在任务完成后执行.
>在Main()中,对CallCount()的调用返回一个Task(使用CallCount()的剩余指令和原始任务)并继续执行.
>如果您不等待此任务完成,则执行inMain()将继续完成程序和正在销毁的任务.
>如果你调用Wait()(如果CallCount()为void你没有等待的任务)你让任务完成,在Main()中执行Count()执行并打印“callCount completed”.

如果你想在CallCount()中等待count任务完成而不返回Main()方法,则调用task.Wait();,所有程序都将等待Count(),但这不是await将要做的.

这个link详细解释了async-await模式.

希望您的代码工作流程图能够帮助您.

enter image description here

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读