Harry Stuart
Harry Stuart

Reputation: 1929

Executing nested async functions at different stages

If I have:

server.Start(socket =>
        {
            socket.doStuff() = async binary =>
            {
                 ...
                 await Method1();
                 ...
                 await Method2();
            };
        }

and the task doStuff() is invoked very frequently (every 20ms), how do I properly execute Method1() on the first doStuff() call and then Method2() on all subsequent doStuff() calls? I have tried using a boolean and if statements such that:

server.Start(socket =>
        {
            socket.doStuff() = async binary =>
            {
                if(firstCall == true)
                {
                   await Method1();
                   firstCall = false;
                }

                else
                await Method2();
            };
        }

However, I was finding that this code was failing because await Method1(); was apparently being called more than once. So it seemed like when the next doStuff() is invoked, Method1() had not yet been awaited from the first doStuff() as it was still executing and therefore, firstCall was still true, causing Method1() to be called again. Is it possible to accomplish this without heaps of booleans? How do I achieve this?

EDIT

To clarify... .doStuff() is invoked everytime the websocket receives a binary message (which occurs every 20ms). I cannot control this, so, working within these bounds: I want to call Method1() only ONCE and I want it to be called on the very first message (the first time .doStuff() is invoked). Every single other time .doStuff() is invoked, I want Method2() to be called and NOT Method1(). I would also like to make sure that once Method1() has been called, it completes before Method2() is called. If I lose some binary data here, it is not an issue.

Upvotes: 0

Views: 71

Answers (1)

Oliver
Oliver

Reputation: 45071

How about something like this:

var beforeFirst = true;

server.Start(socket =>
{
    socket.doStuff = async () =>
    {
        if (beforeFirst) {
            beforeFirst = false;
            await Method1();
            socket.doStuff = Method2;
        }
    };
}
  • When doStuff() is called the first time, it runs Method1().
  • When doStuff() is called while Method1() it does nothing.
  • When Method1() is finished it replaces doStuff() with Method2().

The only bad thing is that the set and read of beforeFirst should maybe be done through some Interlocked method to avoid a race condition at this place.

Upvotes: 1

Related Questions