线程休眠后线程无法启动

时间:2014-08-30 10:37:01

标签: c# .net multithreading

在这里,我正在使用秒表。当秒表值在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]没有它,它会给出单线程异常。

1 个答案:

答案 0 :(得分:2)

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

由于您使用的是.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.
    }
}