线程休眠后线程未启动

本文关键字:线程 启动 休眠 | 更新日期: 2023-09-27 18:20:12

在这个过程中,我使用的是秒表。当秒表值在0到15之间时,它将在屏幕1上播放视频,15之后,它将显示在屏幕0上,但线程在Thread.sleep() 之后没有启动

public partial class Form2 : Form
{
    int[] screentimings = new int[2] { 20, 20 };
    Stopwatch sp;
    Thread thread1;
    //private System.Timers.Timer _timer = new System.Timers.Timer();
    public Form2()
    {
        InitializeComponent();
        thread1 = new Thread(new ThreadStart(A));
       thread1.SetApartmentState(ApartmentState.STA);
        sp = new Stopwatch();
        sp.Start();
        thread1.Start();          
    }
       [STAThread]
    public void showOnMonitor(int showOnMonitor) 
    { 
        Screen[] sc; 
        sc = Screen.AllScreens; 
        Form1 f = new Form1(); 
        f.FormBorderStyle = FormBorderStyle.None; 
        f.Left = sc[showOnMonitor].Bounds.Left; 
        f.Top = sc[showOnMonitor].Bounds.Top;
        f.Height=sc[showOnMonitor].Bounds.Height;
        f.Width=sc[showOnMonitor].Bounds.Width;
        f.StartPosition = FormStartPosition.Manual; 
        f.ShowDialog(); 
    }
    [STAThread]
    private void A()
    {
        long i = sp.Elapsed.Seconds;
        if (i > 0 && i < 15)
        {
            showOnMonitor(1);
        }
        else
        {
            showOnMonitor(0);
        }
        Thread.Sleep(500);
    }
}

showOnMonitor(1)代码已执行,但在15秒后showOnMonitor(0)不起作用。我是线程的新手,不知道它出了什么问题。可能是因为[STAThread]没有这个,它会出现单线程异常。

线程休眠后线程未启动

您根本不需要线程。线程用于同时执行多个操作。解释它将超出这个问题的范围。请在此处阅读更多关于线程的信息。

由于您使用的是.Net 4.5,您可以使用async/await非常容易地来实现您的目标。

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
    protected async override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        await ShowForms();//Show the forms
    }
    private async Task ShowForms()
    {
        ShowOnMonitor(1);
        await Task.Delay(15000);//15 seconds, adjust it for your needs.
        ShowOnMonitor(2);
    }
    private void ShowOnMonitor(int showOnMonitor)
    {
        Screen[] allScreens = Screen.AllScreens;
        Rectangle screenBounds = allScreens[showOnMonitor - 1].Bounds;
        Form1 f = new Form1
        {
            FormBorderStyle = FormBorderStyle.None,
            Left = screenBounds.Left,
            Top = screenBounds.Top,
            Height = screenBounds.Height,
            Width = screenBounds.Width,
            StartPosition = FormStartPosition.Manual
        };
        f.Show();//Use show, not ShowDialog.
    }
}