2014-08-30 77 views
0

在这我使用秒表。当0之间秒表值至15就会起到在屏幕1的视频和15后,将在屏幕上显示0但线程中执行Thread.sleep()线程无法启动后线程Sleeep

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

你的void A没有任何循环,所以它执行一次并且线程结束。 – 2014-08-30 10:41:13

+0

我是新的线程问题可以是愚蠢的。我认为void A()被线程一遍又一遍地调用。 – 2014-08-30 10:44:09

+1

如果你想一次又一次地调用某些东西,你需要使用'Timer'。 – 2014-08-30 10:46:31

回答

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. 
    } 
} 
+0

为什么你使用'async void'而不是'async Task'? 'ShowForms'不是一个事件处理程序。你还应该在'OnLoad'内部'await',所以从'ShowForms'传播的任何异常都不会被处理。 – 2014-09-01 07:26:48

+1

@YuvalItzchakov没理由,它刚刚发生。更新我的答案,谢谢。 – 2014-09-01 07:30:54

+0

@SriramSakthivel我认为它会调用ShowForms()只有一次,但希望它每3秒后定期调用ShowForms()。我尝试使用System.Timer,但因为它运行在多个线程,现在我必须调用所有的过程单线程,因为我使用Windows媒体播放器播放视频和多线程它会引发交叉线程异常 – 2014-09-02 02:24:44