Reputation: 20050
I am developing some system that involves reading messages from some server, registering event handlers and invoking the handlers in turn.
I am using .NET 3.5 so mind you that solution from .NET 4 or async are not available.
The code is similar to this (removed some pieces for brevity):
// Loop until receiving timeout.
while (!timedOut)
{
if ((message = connection.Receive) != null)
{
if (message.Id == Error.MessageId)
{
throw new Exception("Something wrong happened!!");
}
// This calls the event handler (if registered).
HandleEvent(message);
if (finishedEvents)
{
// Finished.
}
else
{
// If message matches the requested message.
if (message.Id == expectedEvents[index].MessageId)
{
index++;
}
// Finished processing all messages.
if (index == expectedEvents.Length)
{
finishedEvents = true;
continue;
}
}
else
{
break;
}
}
Currently i have a synchronous (blocking) implementation where i have a loop that reads the messages and fires the correct handler.
This way, i can verify easily that events are being fired IN ORDER.
I would like to switch to an asynchronous implementation where the events will be fired asynchronously, instead of reading them in a loop.
How can i verify in this implementation that events are received in order? is there a standard solution to this problem?
Upvotes: 2
Views: 90
Reputation: 5553
I think the general design should be something like this (pseudo code):
int currentIndex = 0;
List<myObject> lst = getList();
executor.BeginAsyncTask(lst[currentIndex], AsyncTaskCallBack)
function AsyncTaskCallBack(result)
{
if(result.IsOK)
{
currentIndex+=1;
if(currentIndex < lst.Count)
executor.BeginAsyncTask(lst[currentIndex], AsyncTaskCallBack)
}
}
Using that design, you will process next object only when previous object is finished and it will not block your code. In case you want to do it in ASP.NET, the implemintation may be some different...while you waiting for AsyncTaskCallBack execution, the request proccesing may be finished and already sent tot browser.
Upvotes: 1
Reputation: 62276
Or another solution us Reactive Framework, and use the async calls collection in ForEach
loop, like an ordinary one.
See this answer and online documentation for samples.
Upvotes: 1