Created
July 24, 2018 11:37
-
-
Save Nordes/56c202708df662eb5efab94fb14cc649 to your computer and use it in GitHub Desktop.
Example of semaphoreslim and wait timeout.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Collections.Generic; | |
namespace ConsoleApplication | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
Console.WriteLine("Hello World!"); | |
var lstFun = new List<Semafun>(); | |
lstFun.Add(new Semafun("a")); | |
lstFun.Add(new Semafun("b")); | |
lstFun.Add(new Semafun("c")); | |
lstFun.Add(new Semafun("d")); | |
var taskList = new List<Task>(); | |
foreach (var item in lstFun) | |
{ | |
taskList.Add(item.StartAsync()); | |
//Task.Run(async() => await item.StartAsync()).Wait(); | |
} | |
Task.WhenAll(taskList).Wait(); | |
} | |
} | |
public class Semafun{ | |
private readonly string _name; | |
private readonly TimeSpan MaxTimeout = TimeSpan.FromSeconds(2); | |
public Semafun(string name){ | |
_name = name; | |
} | |
private static SemaphoreSlim Sematest = new SemaphoreSlim(1,1); | |
public async Task StartAsync(){ | |
try { | |
Console.WriteLine("Start " + _name); | |
await Sematest.WaitAsync(MaxTimeout); | |
Console.WriteLine("Wait completed"); | |
var result = _name + " hello"; | |
await Task.Delay(1000).ConfigureAwait(false); | |
Console.WriteLine(result); | |
Sematest.Release(); | |
} catch (Exception e){ | |
Console.WriteLine("Errrrrrrr: " + e.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment