0

In C++, we can use the function

wait_for(lock, delay, []{return i == 1;})) 

with condition variables for synchronization, I start working in a small application using C# (my first contact with C#), and I need the exact same functionality, but I did not find a good substitue to this function.

I there any function that did the exact same behaviour or I need to implement the logic myself ?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
AmigDifo
  • 1
  • 1
  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement – B.O.B. Dec 03 '21 at 08:39
  • 1
    In C# we use a combination of `lock` and `Monitor` to implement condition variables. https://stackoverflow.com/questions/15657637/condition-variables-c-net – Matthew Watson Dec 03 '21 at 08:48
  • Frankly, if you find yourself doing this much at all, you're probably designing something wrong. You shouldn't be polling to check if a condition is met if you can possibly avoid it. Usually the only reason to do this is because you're using some 3rd party product that doesn't provide the proper indication when the actual thing you care about happens (i.e. it doesn't have an event/task/callback/etc. when whatever you care about takes place). If you're polling for a condition you have any control over, you should be providing an event or something so the caller doesn't need to poll. – Servy Dec 03 '21 at 15:01

2 Answers2

0

For asynchronous code I would suggest using Semaphore Slim. It's very fast and easy to use.
As for sync code, easiest way to do such thing would be to use lock statement as Matthew suggested.

quain
  • 861
  • 5
  • 18
0

You wont find exactly the same one-liner for your code. However you might be interested in using the code example

public static async Task WaitUntil(Func<bool> condition, int frequency = 25, int timeout = -1)

from the stackoverflow thread C# Wait until condition is true, which implements the described functionality for C# tasks (not threads).

borealis-c
  • 146
  • 1
  • 6