Software Design

Design de software em C, C++, Java, etc…

C# Delegates

Recently I started a new project, this time with C#. I had never used C# before, so I needed to read a bit about it to get started. The language is very similar to C and Java syntax, very good point ( at least for me ). I also read a bit about threading, synchronization and garbage collection in C# and one cool thing that I thought that we could have in Java is what C# calls delegates.

C# Delegates are like C/C++’s pointer to function. But it’s a little better, because we can chain more than one function pointed by a single delegate object.

Among other things, I needed to write a synchronization mechanism between 2 applications. This synchronization needs to be done every 60 seconds, but the protocol used by the server application is legacy code and is a line-based protocol. So I needed to write a RequestCommand class and a ResponseCommand class both inheriting from Command class.

I needed to send a RequestCommand asynchronously and wait for it’s response. I cannot block the sending thread until the response come because sometimes the server takes time processing a command. So I created a list containing the RequestCommand that were sent and are waiting for a response. When the server returns some response to that command, we get it from the queue and call it’s callback delegate method.

The RequestCommand class is something like that:

public delegate void ResponseCallbackEvent(ResponseCommand response);
public delegate void BeforeSendEvent();
public class ResponseCommand : Command {...}

public class RequestCommand : Command {

  public ResponseCallbackEvent OnResponse { get; set; }
  public BeforeSendEvent BeforeSend { get; set; }

....

}

Note the delegate keyword. It is used to declare a delegate object but also to create it anonymously.

With the classes modeled that way, now when we receive data from server is just a matter of resembling the command line and calling the OnResponse method:

  while ((Running) &&
         (line = reader.ReadLine()) != null)
  {
    ResponseCommand response = new ResponseCommand(line);
    if (waiting.ContainsKey(response.Id))
    {
      RequestCommand request = waiting[response.Id];
      request.OnResponse(response);
      waiting.Remove(response.Id);
    } else {
         ...
    }
  }

When we want to send a request we do the following:

public void MyCallback(ResponseCommand r) {
...
}

public void SendSomeRequests() {
  RequestCommand cmd = new RequestCommand();
  ...
  cmd.OnResponse = MyCallback;

  RequestCommand cmd2 = new RequestCommand();
  ...
  cmd2.OnResponse = delegate(ResponseCommand r) {
    /// this code will be executed when the server respond to the cmd2's request.
  }
}

That’s a very simple way to develop an asynchronous tcp/ip request/response mechanism.

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s

Informação

Publicado em novembro 3, 2011 por em .NET, C#.
%d blogueiros gostam disto: