📜  ASP.NET-多线程

📅  最后修改于: 2020-11-21 05:57:49             🧑  作者: Mango


线程被定义为程序的执行路径。每个线程定义唯一的控制流。如果您的应用程序涉及复杂且耗时的操作(例如数据库访问或某些密集的I / O操作),那么设置不同的执行路径或线程(每个线程执行一个特定的工作)通常会很有帮助。

线程是轻量级进程。使用线程的一个常见示例是现代操作系统对并发编程的实现。使用线程可以节省CPU周期,并提高应用程序的效率。

到目前为止,我们已经编译了程序,其中单个线程作为单个进程运行,这是应用程序的运行实例。但是,通过这种方式,应用程序可以一次执行一项工作。为了使其一次执行多个任务,可以将其划分为较小的线程。

在.Net中,线程是通过’System.Threading’名称空间处理的。通过创建System.Threading.Thread类型的变量,您可以创建一个新的线程来开始使用。它允许您创建和访问程序中的各个线程。

创建线程

通过创建Thread对象并为其构造函数提供ThreadStart引用来创建线程。

ThreadStart childthreat = new ThreadStart(childthreadcall);

线程生命周期

线程的生命周期在创建System.Threading.Thread类的对象时开始,在线程终止或完成执行时结束。

以下是线程生命周期中的各种状态:

  • 未启动状态:创建线程实例但未调用Start方法的情况。

  • 就绪状态:线程准备执行并等待CPU周期时的情况。

  • 不可运行状态:在以下情况下,线程不可运行:

    • 睡眠方法已被调用
    • 等待方法已被调用
    • 被I / O操作阻塞
  • 死状态:这是线程完成执行或已中止的情况。

线程优先级

Thread类的Priority属性指定一个线程相对于另一个线程的优先级。 .Net运行时选择优先级最高的就绪线程。

优先级可以归类为:

  • 超出正常水平
  • 低于一般
  • 最高
  • 最低
  • 正常

创建线程后,将使用线程类的Priority属性设置其优先级。

NewThread.Priority = ThreadPriority.Highest;

线程属性和方法

Thread类具有以下重要属性:

Property Description
CurrentContext Gets the current context in which the thread is executing.
CurrentCulture Gets or sets the culture for the current thread.
CurrentPrinciple Gets or sets the thread’s current principal for role-based security.
CurrentThread Gets the currently running thread.
CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.
ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread.
IsAlive Gets a value indicating the execution status of the current thread.
IsBackground Gets or sets a value indicating whether or not a thread is a background thread.
IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool.
ManagedThreadId Gets a unique identifier for the current managed thread.
Name Gets or sets the name of the thread.
Priority Gets or sets a value indicating the scheduling priority of a thread.
ThreadState Gets a value containing the states of the current thread.

Thread类具有以下重要方法:

Methods Description
Abort Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
AllocateDataSlot Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
AllocateNamedDataSlot Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
BeginCriticalRegion Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might endanger other tasks in the application domain.
BeginThreadAffinity Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.
EndCriticalRegion Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.
EndThreadAffinity Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.
FreeNamedDataSlot Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
GetData Retrieves the value from the specified slot on the current thread, within the current thread’s current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
GetDomain Returns the current domain in which the current thread is running.
GetDomainID Returns a unique application domain identifier.
GetNamedDataSlot Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
Interrupt Interrupts a thread that is in the WaitSleepJoin thread state.
Join Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms.
MemoryBarrier Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
ResetAbort Cancels an Abort requested for the current thread.
SetData Sets the data in the specified slot on the currently running thread, for that thread’s current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead.
Start Starts a thread.
Sleep Makes the thread pause for a period of time.
SpinWait Causes a thread to wait the number of times defined by the iterations parameter.
VolatileRead() Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache. This method has different overloaded forms.
VolatileWrite() Writes a value to a field immediately, so that the value is visible to all processors in the computer. This method has different overloaded forms.
Yield Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.

以下示例说明了Thread类的用法。该页面具有标签控件,用于显示来自子线程的消息。使用Response.Write()方法直接显示来自主程序的消息。因此,它们出现在页面顶部。

源文件如下:


         Untitled Page
      
   
   
   
      

Thread Example

文件后面的代码如下:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;
using System.Threading;

namespace threaddemo
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         ThreadStart childthreat = new ThreadStart(childthreadcall);
         Response.Write("Child Thread Started 
"); Thread child = new Thread(childthreat); child.Start(); Response.Write("Main sleeping for 2 seconds.......
"); Thread.Sleep(2000); Response.Write("
Main aborting child thread
"); child.Abort(); } public void childthreadcall() { try{ lblmessage.Text = "
Child thread started
"; lblmessage.Text += "Child Thread: Coiunting to 10"; for( int i =0; i<10; i++) { Thread.Sleep(500); lblmessage.Text += "
in Child thread "; } lblmessage.Text += "
child thread finished"; }catch(ThreadAbortException e){ lblmessage.Text += "
child thread - exception"; }finally{ lblmessage.Text += "
child thread - unable to catch the exception"; } } } }

注意以下几点

  • 加载页面后,将使用childthreadcall()方法的引用启动一个新线程。主线程活动直接显示在网页上。

  • 第二个线程运行并将消息发送到标签控件。

  • 主线程休眠2000 ms,在此期间执行子线程。

  • 子线程一直运行到被主线程中止为止。它引发ThreadAbortException并终止。

  • 控制返回到主线程。

执行后,程序将发送以下消息:

ASP.NET线程