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 ?

3
  • learn.microsoft.com/en-us/dotnet/csharp/language-reference/… Commented Dec 3, 2021 at 8:39
  • 1
    In C# we use a combination of lock and Monitor to implement condition variables. stackoverflow.com/questions/15657637/condition-variables-c-net Commented Dec 3, 2021 at 8: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. Commented Dec 3, 2021 at 15:01

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.