Avatar of thready
thready
 asked on

c# async wait for event

Hi Experts,

I'd like to write an async method that does this:

while(true) {
     
     await WaitForEventToBeSet(someEvent);  // someEvent auto-resets
     DoWork();
}


Somewhere else in the code:
someEvent.Set();

is this possible with async?  What class can I use?

Thanks a lot!
Mike
C#.NET Programming

Avatar of undefined
Last Comment
thready

8/22/2022 - Mon
it_saige

If I understand what you are trying to accomplish, it would just make more sense to use an AutoResetEvent (or even a Task with a cancellation token).

-saige-
thready

ASKER
Hi it_saige.  That's not really what I'm looking for.  The problem is that that will block.  I wanted to have something that I could await.  I think I'm diving a bit too deep on this one though.  Not sure this is possible.

If you've used async and await, think of it this way, I call some function that loops and waits on an event, but does so asynchronously.
ASKER CERTIFIED SOLUTION
it_saige

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
thready

ASKER
Thanks a lot for your explanation.  

Sorry for taking so long to get back.  I had a broken project for a while after a nuget update...  

I wasn't awaiting the original call that calls this function.  So that one runs off seemingly on its own thread (but not).  I know there's never any other thread involved, but I was hoping somehow it would magically be able to wait for an event after "skipping over" the original call and getting to the stuff that will cause events to be set which would wake up my "thread" (without actually using a thread).  This will work if I don't block....  So I guess I could just put a wait with a timeout.  Would be totally cool to be able to do it with interrupts though.

Basically, the loop was just a provider that updates the UI asynchronously whenever events are fired off to it, and it also throttles how often it updates the UI by awaiting Task.Delay making sure a minimum time has passed before updating again...  But I guess I've answered my own question here with the wait with timeout...  Not what I was hoping for though.  Maybe you'll have something better for me?
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
thready

ASKER
Nope - I cannot do this because I'm eating away at processing time...  I guess I need a real thread unless you can see another way.  I've been kind of overdoing it with async and await because of the simplicity but maybe this is just getting silly.