Class Instantiation with Unique Object Name in an Event Handler method (at runtime)
I have searched around a lot for a solution, but could not find any. I have a server application (in .NET) that receives video streams from multiple devices. The library tha开发者_Go百科t I am using to decode and process the stream is not thread-safe. The name of my library is "VideoProcessor" with a VideoProcessor class.
In my main program, I would like to create an instance of VideoProcessor for each device. My first approach was to have a connection event handler that instantiates VideoProcessor for the new device. However, it would never work when more than one device tries to connect. Please refer to the code snippet below:
static void HandleVideoConnectionEvent(int port, string deviceId)
{
VideoProcessor vid = new VideoProcessor(port, deviceId);
}
As you can see, I will overwrite vid everytime a new device connects. I have run out of ideas. I need to have a separate instance of VideoProcessor running for each device and I have to keep track of which instance is being used for which device. My last hope is to spawn a new process for a new device connection and maintain a list of deviceIDs and their corresponding PID (I don't know if this is possible in .NET). Please help. There must be a neat way of doing this. Thank you very much in advance for your time.
Regards.
Use a Dictionary class:
static Dictionary<string, VideoProcessor> processors =
new Dictionary<string, VideoProcessor();
static void HandleVideoConnectionEvent(int port, string deviceId)
{
processors.Add(deviceId, new VideoProcessor(port, deviceId));
}
Then you can lookup a VideoConnection class by the deviceId. Such as:
static VideoProcessor GetVideoProcessor(string deviceId)
{
return processors[deviceId];
}
Of course, you will need to do sanity checks, like making sure that the deviceId doesn't already exist in the dictionary (a dictionary has to have unique keys, or unique deviceIds, and making sure when you try to get it from the dictionary, that the deviceId actually exists)
精彩评论