Vishwas
Vishwas

Reputation: 1541

Not seeing output after using Task delay

I am using an online editor for testing some C# code : https://repl.it/ I am not able to get the task after Task.Delay. Why is this C# code not working as intended?

using System.IO;
using System;
using System.Reflection;
using System.Threading.Tasks;

class Input {

   public Input() {

   }

   public async void  hello()
   {
    Console.WriteLine("some task");
   await Task.Delay(1000);
   Console.WriteLine("after some time");
     }


}

class SomeExample {
   public static void Main(string[] args) {

      Input std1 = new Input( );
      std1.hello();
   }
}

Upvotes: 0

Views: 176

Answers (3)

Vishwas
Vishwas

Reputation: 1541

For now it seems this code is doing my work. I don't need to use async or Task keywords.

using System.IO;
using System;

using System.Threading.Tasks;
class Input
{
    public Input()
    {

    }

    public void   hello()
    {
        Console.WriteLine("some task");
           Task.Delay(1000).Wait();
        Console.WriteLine("after some time");

    }


}

class SomeExample
{
    public static void Main(string[] args)
    {
        Input std1 = new Input();
        std1.hello() ;

    }
}

Upvotes: -1

sachin soni
sachin soni

Reputation: 541

Fixes: Change your method return type from void to Task. Make the console wait by adding Console.ReadLine() so that you can see the output ("after some time") and lastly, tell the method to wait and don't finish execution by adding Wait(). Hope this works.

class Input
{
    public Input()
    {

    }

    public async Task hello()
    {
        Console.WriteLine("some task");
        await Task.Delay(1000);
        Console.WriteLine("after some time");
        Console.ReadLine();
    }
}

class SomeExample
{
    public static void Main(string[] args)
    {
        Input std1 = new Input();
        std1.hello().Wait();
    }
}

Upvotes: 0

Alexander Goldabin
Alexander Goldabin

Reputation: 1933

Method hello should return Task, not void. Method Main should be async Task to be able to await hello. Also you need to await std1.hello() call:

public async Task hello()
{
    Console.WriteLine("some task");
    await Task.Delay(1000);
    Console.WriteLine("after some time");
}

public static async Task Main(string[] args) 
{
  Input std1 = new Input( );
  await std1.hello();
}

What you have now is situation when Main method finishes its execution before hello method (because it not awaited).

Upvotes: 2

Related Questions