Waiting for something to happen - asynchronous or synchronous model?

I have this method WaitForReaderArrivalthat looks like this: (works all the time, waiting for the reader to arrive)

        public void WaitForReaderArrival()
        {
            do
            {
                if (ReaderArrived())
                {
                    break;
                }

                System.Threading.Thread.Sleep(1000);
            } while (ReaderArrived() == false);
        }

And I'm waiting for the reader to come using

 await Task.Run(new Action(WaitForReaderArrival));
 if (ReaderArrived())
 {
      //Raise an ReaderArrived here!
    ..//blah blah
 }

One of my employees asked me to change the above line only to

 WaitForReaderArrival(); 
 if (ReaderArrived())
 {
    //Raise an ReaderArrived here!
    ..//blah blah
 }

The question arises:

  • Is the asynchronous model that I adopted above not very useful? Why she asked me to change this line to the usual synchronous methodology is still a question for me.

  • What in the above correct way to wait for something to happen and then continue?

+3
source share
4 answers

, , ? .

, , - , - . , , await Task.Run, , Task.Delay:

public async Task WaitForReaderArrivalAsync()
{
    while (!ReaderArrived())
    {
        await Task.Delay(1000).ConfigureAwait(false);
    }
}

... - , - , ?

. WaitForReaderArrival await Task.Run WaitForReaderArrivalAsync().Wait(), . , "Async All the Way" :

// top-level event handler
async void Button_Click(object sender, EventArgs e)
{
    await WaitForReaderArrivalAsync();
    MessageBox.Show("ReaderArrived!");
}

. , ReaderArrived , async/await .

: -, DoEvents, , :

public void WaitForReaderArrival()
{
    while (!ReaderArrived())
    {
        Application.DoEvents();
        System.Threading.Thread.Sleep(100);
    }
}

: .DoEvents.

+5

. , .

. "" . , , , .

, , , . "".

, , , do . .

, if (ReaderArrived()) . , .

" ". .

, , .:)

+2

, , , - .

0

, - , ?

( a.k.a.) :

public void WaitForReaderArrival(Action callback)
{
    do
    {
        if ( ReaderArrived() )
        {
            break;
        }

        System.Threading.Thread.Sleep(1000);
    } while ( ReaderArrived() == false );

    callback();
}

:

WaitForReaderArrival(() =>
    {
        // Raise an ReaderArrived here!
        // ...blah blah
    });

, , ? .

, - Reader. , .

, Thread.Sleep() . , .

0

All Articles