没有表单的c#交叉线程

本文关键字:线程 表单 | 更新日期: 2023-09-27 18:04:17

我有一个应用程序可以打开和关闭你的摄像头。它打开它,在一个新的线程,我试图使一个按钮的工作从主代码关闭它,但交叉线程不工作,因为他们是没有形式,我不能调用。下面是代码:

public class Program
{
    public static FilterInfoCollection CaptureDevicesList;
    public static VideoSourcePlayer videoSourcePlayer = new VideoSourcePlayer();
    public static VideoCaptureDevice videoSource;
    public static System.Timers.Timer TimerClose = new System.Timers.Timer();
    [STAThread]
    static void Main()
    {
        TimerClose.Elapsed += (o, e) => TimerClose_Tick();
        TimerClose.Interval = 10000;
        TimerClose.Start();
        new Thread(() =>
        {
            Thread.CurrentThread.IsBackground = true;
            CaptureDevicesList = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            Class1.oncam();
        }).Start();
        Application.Run();
    }
    private static void TimerClose_Tick()
    {
        Class1.CloseCurrentVideoSource(); // <--- function cant run
    }
}

所以我想做的是让close函数工作,它试图关闭在不同线程上运行的网络摄像头。这是class1:

    class Class1
{
    public static void oncam()
    {
        Program.videoSource = new VideoCaptureDevice(Program.CaptureDevicesList[0].MonikerString);
        OpenVideoSource(Program.videoSource);
    }
    public static void OpenVideoSource(IVideoSource source)
    {
        CloseCurrentVideoSource();
        Program.videoSourcePlayer.VideoSource = source;
        Program.videoSourcePlayer.Start();
    }
    public static void CloseCurrentVideoSource()
    {
        if (Program.videoSourcePlayer.VideoSource != null)
        {
            Program.videoSourcePlayer.SignalToStop();
            for (int i = 0; i < 30; i++)
            {
                if (!Program.videoSourcePlayer.IsRunning)
                    break;
                System.Threading.Thread.Sleep(100);
            }
            if (Program.videoSourcePlayer.IsRunning)
            {
                Program.videoSourcePlayer.Stop();
            }
            Program.videoSourcePlayer.VideoSource = null;
        }
    }
}

感谢您的帮助

没有表单的c#交叉线程

VideoSourcePlayer继承自System.Windows.Forms.Control,因此跨线程访问需要同步。

当从另一个线程访问该控件时,调用Invoke