Asp.net-multi-threading

提供:Dev Guides
移動先:案内検索

ASP.NET-マルチスレッド

スレッドは、プログラムの実行パスとして定義されます。 各スレッドは、制御の一意のフローを定義します。 アプリケーションがデータベースアクセスや集中的なI/O操作などの複雑で時間のかかる操作を伴う場合、各スレッドが特定のジョブを実行する異なる実行パスまたはスレッドを設定すると役立つことがよくあります。

スレッドは軽量のプロセスです。 スレッドの一般的な使用例の1つは、最新のオペレーティングシステムによる並行プログラミングの実装です。 スレッドを使用すると、CPUサイクルの無駄が節約され、アプリケーションの効率が向上します。

これまで、単一スレッドがアプリケーションの実行インスタンスである単一プロセスとして実行されるプログラムをコンパイルしました。 ただし、この方法では、アプリケーションは一度に1つのジョブを実行できます。 一度に複数のタスクを実行するには、より小さなスレッドに分割できます。

スレッドを作成する

Netでは、スレッドは「System.Threading」名前空間を介して処理されます。 _System.Threading.Thread_型の変数を作成すると、作業を開始する新しいスレッドを作成できます。 プログラム内の個々のスレッドを作成してアクセスできます。.

スレッドは、Threadオブジェクトを作成し、そのコンストラクターにThreadStart参照を与えることで作成されます。

ThreadStart childthreat = new ThreadStart(childthreadcall);

スレッドのライフサイクル

スレッドのライフサイクルは、System.Threading.Threadクラスのオブジェクトが作成されると開始され、スレッドが終了または実行を完了すると終了します。

スレッドのライフサイクルにおけるさまざまな状態を次に示します。

  • 未開始状態:スレッドのインスタンスは作成されているが、Startメソッドが呼び出されていない状態です。
  • 準備完了状態:スレッドの実行準備ができ、CPUサイクルを待機している状態です。
  • 実行不可能な状態:次の場合、スレッドは実行可能ではありません。
  • Sleepメソッドが呼び出されました
  • 待機メソッドが呼び出されました
  • I/O操作によってブロックされました
  • デッド状態:スレッドが実行を完了したか、中止された状態です。

スレッドの優先度

ThreadクラスのPriorityプロパティは、他のスレッドに対する1つのスレッドの優先度を指定します。 .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()メソッドを使用して直接表示されます。 したがって、それらはページの上部に表示されます。

ソースファイルは次のとおりです。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="threaddemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

   <head runat="server">
      <title>
         Untitled Page
      </title>
   </head>

   <body>
      <form id="form1" runat="server">
         <div>
            <h3>Thread Example</h3>
         </div>

         <asp:Label ID="lblmessage" runat="server" Text="Label">
         </asp:Label>
      </form>
   </body>

</html>

コードビハインドファイルは次のとおりです。

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 <br/>");
         Thread child = new Thread(childthreat);

         child.Start();

         Response.Write("Main sleeping  for 2 seconds.......<br/>");
         Thread.Sleep(2000);
         Response.Write("<br/>Main aborting child thread<br/>");

         child.Abort();
      }

      public void childthreadcall()
      {
         try{
            lblmessage.Text = "<br/>Child thread started <br/>";
            lblmessage.Text += "Child Thread: Coiunting to 10";

            for( int i =0; i<10; i++)
            {
               Thread.Sleep(500);
               lblmessage.Text += "<br/> in Child thread </br>";
            }

            lblmessage.Text += "<br/> child thread finished";

         }catch(ThreadAbortException e){

            lblmessage.Text += "<br/> child thread - exception";

         }finally{
            lblmessage.Text += "<br/> child thread - unable to catch the  exception";
         }
      }
   }
}

以下を観察してください

  • ページがロードされると、childthreadcall()メソッドの参照を使用して新しいスレッドが開始されます。 メインスレッドアクティビティは、Webページに直接表示されます。
  • 2番目のスレッドが実行され、メッセージがラベルコントロールに送信されます。
  • メインスレッドは2000ミリ秒間スリープし、その間、子スレッドが実行されます。
  • 子スレッドは、メインスレッドによって中止されるまで実行されます。 ThreadAbortExceptionを発生させて終了します。
  • 制御はメインスレッドに戻ります。

実行されると、プログラムは次のメッセージを送信します。

ASP.NETスレッド