为什么只有我的任务工作一次? [英] Why my task work only once?

查看:106
本文介绍了为什么只有我的任务工作一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印每2秒号码,但并最终我只得到0我需要做的就是这每2秒?

结果:

  0
    1
    。
    。
    49


 私有静态无效的主要(字串[] args){
    发送();
  }  公共静态异步任务的send(){
    的for(int i = 0; I< 50;我++){
        Console.WriteLine(ⅰ);
        等待Task.Delay(2000);
    }
  }


解决方案

很好,只是因为你的方法不会等待发送的方法来完成,你可以'T使用等待关键字,以便为实现这一目标发生了,因为编译器将不允许异步 ,在这种情况下你可以简单的使用 Task.Run

 私有静态无效的主要(字串[] args)
    {
        Task.Run(异步()=>
        {
            等待发送();
        })。等待();
    }    公共静态异步任务发送()
    {
        的for(int i = 0; I< 50;我++)
        {
            Console.WriteLine(ⅰ);
            等待Task.Delay(2000);
        }
    }

I want to print every 2 sec number but and in the end i get only 0 what i need to do to get this every 2 sec?

result:

    0
    1
    .
    .
    49


  private static void Main(string[] args) {
    Send();
  }

  public static async Task Send() {
    for (int i = 0; i < 50; i++) {
        Console.WriteLine(i);
        await Task.Delay(2000);
    }
  }

解决方案

well, simply because your Main method won't wait for the send method to finish and you can't use the await keyword in order for that to happened since the compiler won't allow an async Main, in that case you could simple use a Task.Run

 private static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            await Send();
        }).Wait();
    }

    public static async Task Send()
    {
        for (int i = 0; i < 50; i++)
        {
            Console.WriteLine(i);
            await Task.Delay(2000);
        }
    }

这篇关于为什么只有我的任务工作一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆