Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Async Tasks In Console App

using System.IO;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Console.WriteLine("Tasks...");
        
        StartTasks().GetAwaiter().GetResult();
        
        
        Console.WriteLine("End");
    }
    
    
   static List<Task<bool>>  _tasks=new List<Task<bool>>();
    
    
    private async static Task StartTasks(int count=10)
    {
        
        for(var i=1;i<=count;i++)
        {
            _tasks.Add(DoTask(i,i*3));        
        }
        
        
        try
        {
            
            await Task.WhenAll(_tasks);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        
        
        
    }
    
    private async static Task<bool> DoTask(int no,int runCount=10)
    {
        
        var x=1;
        
        while(true)
        {
            
            try
            {
                
                Console.WriteLine($"{no} - doing some tasks..." + x);
                await Task.Delay(1000*1);
                
            }
            catch(OperationCanceledException)
            {
                break;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
            x++;
            
            if(x>=runCount) break;
        }
        
        
        return true;
        
        
    }
    
    
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.