Use delegate as async callback - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Async

Description

Use delegate as async callback

Demo Code

using System;/*from   w w w  . j  a  v a 2  s  . c o m*/
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading;
class Program
{
   static void Main(string[] args)
   {
      Machine machine = new Machine();
      machine.RegisterTempWatcher(LogTempToConsole);
      machine.RegisterTempWatcher(LogTempToFile);
      machine.TurnOn();
   }
   private static void LogTempToConsole(double prev, double current)
   {
      Console.WriteLine($"Temperature changed from {prev} to {current}");
   }
   private static async void LogTempToFile(double prev, double current)
   {
      using (StreamWriter writer = new StreamWriter("temps.txt", true))
      {
         await writer.WriteLineAsync($"Machine temperature changed from {prev} to {current}");
      }
   }
}
public delegate void TempChanged(double prev, double current);
public class Machine
{
   private double _currentTemp = 36;
   private TempChanged _tempChanged;
   public double CurrentTemp
   {
      get
      {
         return _currentTemp;
      }
      set
      {
         if (_currentTemp != value)
         {
            var prev = _currentTemp;
            _currentTemp = value;
            OnTempChanged(prev, value);
         }
      }
   }
   public void TurnOn()
   {
      while (CurrentTemp < 100)
      {
         Thread.Sleep(1000);
         CurrentTemp++;
      }
   }
   public void RegisterTempWatcher(TempChanged watcher)
   {
      _tempChanged += watcher;
   }
   private void OnTempChanged(double prev, double current)
   {
      if(_tempChanged != null)
      {
         _tempChanged(prev, current);
      }
   }
}

Result


Related Tutorials