如何在 WPF 应用程序中使用 Thread.Sleep?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21181436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:32:32  来源:igfitidea点击:

How to use Thread.Sleep in WPF application?

c#.netwpfprinting

提问by GibboK

In a WPF application VS 2010, I basically need to print a document and check for errors after few seconds it start to print.

在 WPF 应用程序 VS 2010 中,我基本上需要打印文档并在几秒钟后开始打印时检查错误。

At the moment I am using Thread.Sleep(2000)but it does not work. The trycode I believe is running in the UI thread.

目前我正在使用,Thread.Sleep(2000)但它不起作用。该try相信代码在UI线程中运行。

Any idea how to fix it? Or better approach?

知道如何修复它吗?或者更好的方法?

In this specific case I do not care if the UI Thread is blocked for few seconds.

在这种特定情况下,我不在乎 UI 线程是否被阻塞了几秒钟。

try
{
    printer = new Printer();
    printer.PrintTicket(dataAdv);
    // check eventual problem during printing like paper jamp
    Thread.Sleep(2000);
    if (monitorPrinter.IsPrinterReady() == false)
    {
        isPrinterReady = false;
        MessageBox.Show("Problem during the printing!!!");
    }
}

回答by GibboK

Solution to my problem thanks all for pointing me out in the right direction.

我的问题的解决方案感谢所有人为我指出正确的方向。

try
{
   printer = new Printer();
   printer.PrintTicket(dataAdv);

   System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
   dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
   dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
   dispatcherTimer.Start();
}

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
   if (monitorPrinter.IsPrinterReady() == false)
   {
      MessageBox.Show("SOME PROBLEM WHEN PRINTING!");
   }
}