mercredi 9 mars 2016

How to queue incoming events in event handler while waiting for user's response

I use C#, .NET Framework 4.5, VS2015.

I implement an event handler for event (TcpRequest) that is fired by a black-boxed module. My event handler call a private method that fires an event to client/GUI and waiting for user's response. Meanwhile the black-boxed module keeps firing TcpRequest event. Somehow I need to queue the incoming events while waiting. As soon as the user gives response for the first event, the queue can be "flushed". I don't know how to implement that.

Is there any design pattern or best practice for such case?

Following are my codes. Please feel free to modify them. Thank you in advance.

public void TcpRequestHandler(int id, CONN_INFO connInfo)
{
    if (SomeCondition)
    {
        var myArgs = new MyEventArgs()
        {
            Id = id,
            ConnInfo = connInfo
        }

        // this the way I tried and I know it is wrong
        lock (_eventQueue)
        {
            _eventQueue.Add(myArgs);
        }
        FireEventToClient(myArgs);
    }
}

private void FireEventToClient(MyEventArgs myArgs)
{
    EventToClient(this, myArgs);
    if (myArgs.Continue)
    {
        // "flush" the event queue
        ...
        // do other things
        ...
    }
}

public class MyEventArgs : EventArgs
{
    public int Id {get; private set;}
    public CONN_INFO ConnInfo {get; private set;}
    public bool Continue {get; set;} 
}

Aucun commentaire:

Enregistrer un commentaire