CSharp examples for Thread Asynchronous:Async
Pass in async lambda
using System;/*w ww . j a v a 2s . com*/ using System.IO; using System.Threading; class Program { static void Main(string[] args) { Machine machine = new Machine(); machine.RegisterTempWatcher((double prev, double current) => { Console.WriteLine($"Temperature changed from {prev} to {current}"); }); machine.RegisterTempWatcher(async (double prev, double current) => { using (StreamWriter writer = new StreamWriter("temps.txt", true)) { await writer.WriteLineAsync($"Machine temperature changed from {prev} to {current}"); } }); machine.TurnOn(); } } 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); } } }