views:

52

answers:

1

Hi All, I am working on a C# windows application. This application is mainly related to sockets.

I have a class called tcpsocket, which handles all socket level functionality of sending, receiving data, etc. A controller class calls this tcpsocket. In addition, it does all other work of logging data to a file and updating GUI. I thought it will be good to have this controller in the backgroundworker, to ensure that gui is responsive at all times. First of all, is it a good idea to do this?

As i am trying to do this, i am facing a problem regarding the progresschanged handler for the backgroundworker. I want to be able to display connection status (type: String) in a text field and data being sent/received by the application (type: Byte[]) in richTextBox. Since the controller can only send data to gui through the progressChanged event, how do i pass different types of data (String/byte[]) to the gui?

A: 

Hi,

If you decide to run the controller on a different thread other than the UI thread you will need to hook the progressChanged event from the controller to a method handler on the UI thread. Once you have done this you will have to marshal the data returned from the processChanged event to the UI thread. Below is an example of how to do the marshaling.

private object _lock = new object(); //should have class scope

private void DispalyMessage(byte[] bytes)
{
  if (this.InvokeRequired)
  {
    lock (_lock)
    {
      EventHandler d = new EventHandler(DispalyMessage);
      this.Invoke(d, new object[] { bytes });
      return;
    }
  }
  else
  {
    //the bytes data has been marshaled from the controller class thread to the ui thread and can be used at will to populate a memeber of the ui.
  }
}

Additionally you might need to modify your controller and add different events which might return something other than a type:byte[]. You can do this by simply be leveraging the generic delegate class which is part of the .net framework or you can leverage the delegate class directly. Here is the Microsoft documentation on delegates.

Enjoy!

Doug
So to make sure i understand, i will have events firing data of different types and processHandler is kind of one of the events. Am i correct?
Batul
Yes, If you need to pass a datatype other then byte you can just created different types of events from your controller class and point them to different handler on the UI thread.
Doug
Thanks, that sounds good. I am thinking i will use the processChangedHandler to display only the status of the link (Connected/Disconnected) and use events for all other data. Thanks a lot.... It is much more clear to me now.
Batul
Sounds good glad the info was helpful - yea i agree with your approach - better to have event that do what they say they are going to do instead of having one uber event that passes the kitchen sink so to speak - Enjoy!
Doug