简体   繁体   English

C#如何使用多个对象的事件处理程序?

[英]C# How to use an Event Handler from multiple objects?

Apologies as I have never used event handlers before, and don't know how to phrase the question yet. 道歉,因为我以前从未使用过事件处理程序,也不知道该如何表达问题。 I understand the concept of them. 我了解他们的概念。

I am working on a video file processing tool which processes videos frame by frame. 我正在使用一种视频文件处理工具,可以逐帧处理视频。 The user selects a group of videos, and the application will run this code to loop through them and and trigger processing on each one: 用户选择一组视频,应用程序将运行以下代码以循环浏览它们并触发每个视频的处理:

foreach (string[] item in fileList)
{
    FileVideoSource videoSource;
    videoSource = new FileVideoSource(item[1]);
    videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
    videoSource.Start();
}

This directs each new frame that is processed to the event handler called "video_NewFrame". 这会将处理的每个新帧定向到称为“ video_NewFrame”的事件处理程序。

The event handler looks like this: 事件处理程序如下所示:

private void video_NewFrame(object sender, NewFrameEventArgs eventArgs) {
    try {
        this.Invoke((MethodInvoker) delegate {
            // get new frame
            Bitmap bitmap = eventArgs.Frame;

            //Process frame code...

            pictureBox1.Image = bitmap;
            Application.DoEvents();
        });
    } catch {
        Application.Exit();
    }
}

Now there will be multiple files in the fileList which need to be processed. 现在,fileList中将有多个文件需要处理。 (I plan to use threading in the future). (我计划将来使用线程)。

Currently this code will process all of the frames together, rather than separately for each video. 当前,此代码将一起处理所有帧,而不是针对每个视频单独处理。 How can I separate the objects for the event handler to process the objects individually? 如何为事件处理程序分离对象,以便分别处理对象?

What you should do is create a class whose constructor receives the string.. all the class does is what the body of the loop does, but registers his instance method for handling the event.. you just need to instantiate the classes in the loop body and keep them in scope for as long as necessary. 您应该做的是创建一个类,该类的构造函数接收该字符串。.该类所做的所有事情都是循环主体所做的,但是注册其实例方法以处理该事件..您只需在循环主体中实例化这些类即可。并在必要时将其保留在范围内。

class VideoProcessor
{
  private FileVideoSource videoSource;

  public VideoProcessor(string fileName)
  {
    videoSource = new FileVideoSource(fileName);        
  }

  public void Start()
  {
    videoSource.NewFrame += video_NewFrame;
    videoSource.Start();
  }

  private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
  {

  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM