zoukankan      html  css  js  c++  java
  • CLR via C# 读书笔记 13 前台线程和后台线程

    前台线程(Foreground)

    后台线程(Background)

    相互作用:

      当所有前台线程退出的时候, CLR会强制终止所有的后台线程,并且不会有异常抛出

    请参考以下代码(摘自CLR via C# ):

    代码
    using System;
    using System.Threading;
    public static class Program
    {
    public static void Main()
    {
    // Create a new thread (defaults to foreground)
    Thread t = new Thread(Worker);
    // Make the thread a background thread
    t.IsBackground = false;
    t.Start();
    // Start the thread
    // If t is a foreground thread, the application won't die for about 10 seconds
    // If t is a background thread, the application dies immediately
    Console.WriteLine("Returning from Main");
    }
    private static void Worker()
    {
    Thread.Sleep(
    10000); // Simulate doing 10 seconds of work
    // The line below only gets displayed if this code is executed by a foreground thread
    Console.WriteLine("Returning from Worker");
    }
    }

    转换

      你可以在任何时候转换前台线程为后台线程,或者反过来. 只要线程还活着

    默认值:

      主线程默认是前台线程

      线程池默认是后台线程

      新建的默认是后台线程

    何时使用?

      非关键性事务或者可恢复性质的事务,可以使用后台线程

    PS1:实际上用前台线程的情况并不多,因为实际上还要考虑用户直接干掉整个进程的情况

    PS2:在服务器压力很大或者服务器有某种不可预知缺陷的情况下,后台线程出问题的几率会比前台线程大(例如莫名其妙不运行啦 什么的)  ,  这条只是个人意见 没有经过非常严格的检验

  • 相关阅读:
    MySQL 存储过程
    linux iptables 相关设置
    Ubuntu iptables 设置
    Mac OS 10.12
    解决:cc1.exe: sorry, unimplemented: 64-bit mode not compiled in
    go get golang.org/x/net 安装失败的解决方法!
    Ubuntu16.04
    Ubuntu16.04
    Ubuntu16.04
    在Ubuntu16.04里面安装Gogland!
  • 原文地址:https://www.cnblogs.com/PurpleTide/p/1875838.html
Copyright © 2011-2022 走看看