导出 (0) 打印
全部展开
信息
您所需的主题如下所示。但此主题未包含在此库中。

Thread.IsBackground 属性

2013/12/13

获取或设置一个值,该值指示某个线程是否为后台线程。

Namespace:  System.Threading
程序集:  mscorlib(位于 mscorlib.dll 中)

public bool IsBackground { get; set; }

属性值

类型: System.Boolean
如果此线程是后台线程或即将成为后台线程,则为 true;否则为 false

异常条件
ThreadStateException

已经终止线程的执行。

一个线程或者是后台线程或者是前台线程。在 Windows Phone 中,这两者的行为没有区别。

下面的示例演示如何启动前台和后台线程。该示例使用 Thread(ParameterizedThreadStart) 构造函数创建两个线程。其中一个线程作为前台线程运行(默认设置),另一个线程更改为后台线程(通过将其 IsBackground 属性设置为 true)。该示例还通过调用 QueueUserWorkItem 方法启动线程池线程。线程池线程是后台线程。

所有这三个线程都显示其 IsBackground 属性值。

说明注意:

要运行此示例,请参见生成具有静态 Windows Phone TextBlock 控件的示例


using System;
using System.Threading;
using System.Windows.Input;

public class Example
{
   private static System.Windows.Controls.TextBlock outputBlock;

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      Example.outputBlock = outputBlock;
      outputBlock.Text = "Click here to begin the demo.\n";

      outputBlock.MouseLeftButtonUp += new MouseButtonEventHandler(MouseUp);
   }

   private static void MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
   {
      outputBlock.MouseLeftButtonUp -= new MouseButtonEventHandler(MouseUp);
      outputBlock.Text = "To run the demo again, refresh the page.\n\n";

      Thread backgroundThread = new Thread(RunLoop);
      backgroundThread.Name = "BackgroundThread";
      backgroundThread.IsBackground = true;
      backgroundThread.Start(null);

      Thread foregroundThread = new Thread(RunLoop);
      foregroundThread.Name = "ForegroundThread";
      foregroundThread.Start(null);

      ThreadPool.QueueUserWorkItem(RunLoop);
   }

   private static void RunLoop(object state)
   {
      string threadName = Thread.CurrentThread.Name;
      if (threadName==null) {threadName = "<ThreadPool thread>";}

      outputBlock.Dispatcher.BeginInvoke(displayHelper, 
         String.Format("{0} is running. IsBackground = {1}\n", 
                       threadName, Thread.CurrentThread.IsBackground));
   }

   // In order to update the TextBlock object, which is on the UI thread, you must
   // make a cross-thread call by using the Dispatcher object that is associated 
   // with the TextBlock. The DisplayOutput helper method and its delegate, 
   // displayHelper, are used by the BeginInvoke method of the Dispatcher object
   // to append text to the TextBlock. 
   //
   private static Action<string> displayHelper = new Action<string>(DisplayOutput);
   private static void DisplayOutput(string msg)
   {
      outputBlock.Text += msg;
   }
}

/* This example produces output similar to the following:

BackgroundThread is running. IsBackground = True.
ForegroundThread is running. IsBackground = False.
<ThreadPool thread> is running. IsBackground = True.
 */


Windows Phone OS

受以下版本支持: 8.0, 7.1, 7.0

Windows Phone

显示:
© 2015 Microsoft