Timer.Stopとは? わかりやすく解説

Timer.Stop メソッド

Enabledfalse設定すると、Elapsed イベントの発生停止します

名前空間: System.Timers
アセンブリ: System (system.dll 内)
構文構文

解説解説
使用例使用例

実行中の Elapsed イベント終了するまで Stop メソッド呼び出すスレッド継続しないようにする方法、および 2 つElapsed イベントイベント ハンドラ同時に実行する状況 (再入ともいう) が発生しないようにする方法を、次のコード例示します

この例では、テスト100実行しますテスト実行するたびに、150 ミリ秒間隔設定したタイマ開始されます。イベント ハンドラは Thread.Sleep メソッド使用して長さ50200 ミリ秒範囲ランダムに変化するタスクシミュレートます。また、テスト メソッドは、1 秒待機してからタイマ停止するコントロール スレッド開始しますタイマ停止時イベントが処理中である場合は、コントロール スレッドイベント終了するまで待ち、それから処理を継続する必要があります

再入を防ぎイベント終了するまでコントロール スレッドが処理を継続できないようにするために、Interlocked.CompareExchange(Int32,Int32,Int32) メソッドオーバーロード使用してます。イベント ハンドラCompareExchange(Int32,Int32,Int32) メソッド使用してコントロール変数を 1 に設定します (現在の値がゼロ場合のみ)。これは分割不可能な操作です。戻り値ゼロ場合コントロール変数は 1 に設定されており、イベント ハンドラは処理を続けます戻り値ゼロ以外の場合は、再入を避けるためにイベントを単に破棄します(すべてのイベント実行する必要がある場合は、Monitor クラス使用してイベント同期する方法お勧めします)。イベント ハンドラ終了するとき、コントロール変数ゼロ戻します。この例では、実行したイベント総数、再入により破棄したイベント総数、および Stop メソッド呼び出し後に発生したイベント総数記録してます。

コントロール スレッドCompareExchange(Int32,Int32,Int32) メソッド使用してコントロール変数を -1 (マイナス 1) に設定します (現在の値がゼロ場合のみ)。分割不可能な操作からの戻り値ゼロ以外の場合は、イベント実行中です。コントロール スレッドはしばらく待機してから、再試行ます。この例では、イベント終了するまでコントロール スレッド待機した回数総数記録してます。

Imports System
Imports System.Timers
Imports System.Threading

Public Module Test
    
    ' Change these values to control the behavior of the program.
    Private testRuns As Integer
 = 100 
    ' Times are given in milliseconds:
    Private testRunsFor As Integer
 = 1000
    Private timerInterval As Integer
 = 150

    ' Qualify the name to avoid confusion with the
    ' System.Threading.Timer class.
    Private WithEvents Timer1 As
 New System.Timers.Timer
    Private rand As New
 Random()

    ' This is the synchronization point that prevents events
    ' from running concurrently, and prevents the main thread 
    ' from executing code after the Stop method until any 
    ' event handlers are done executing.
    Private syncPoint As Integer
 = 0

    ' Count the number of times the event handler is called,
    ' is executed, is skipped, or is called after Stop.
    Private numEvents As Integer
 = 0
    Private numExecuted As Integer
 = 0
    Private numSkipped As Integer
 = 0
    Private numLate As Integer
 = 0

    ' Count the number of times the thread that calls Stop
    ' has to wait for an Elapsed event to finish.
    Private numWaits As Integer
 = 0

    <MTAThread> _
    Sub Main()
        Timer1.Interval = timerInterval

        Console.WriteLine()
        For i As Integer
 = 1 To testRuns
            TestRun
            Console.Write(vbCr & "Test {0}/{1}    ",
 i, testRuns)
        Next

        Console.WriteLine("{0} test runs completed.",
 testRuns)
        Console.WriteLine("{0} events were raised.",
 numEvents)
        Console.WriteLine("{0} events executed.",
 numExecuted)
        Console.WriteLine("{0} events were skipped for concurrency.",
 numSkipped)
        Console.WriteLine("{0} events were skipped because they
 were late.", numLate)
        Console.WriteLine("Control thread waited {0} times for
 an event to complete.", numWaits)
    End Sub

    Sub TestRun()
        ' Set syncPoint to zero before starting the test 
        ' run. 
        syncPoint = 0

        Timer1.Enabled = True

        ' Start the control thread that shuts off the timer.
        Dim t As New Thread(AddressOf
 ControlThreadProc)
        t.Start()

        ' Wait until the control thread is done before proceeding.
        ' This keeps the test runs from overlapping.
        t.Join()

    End Sub

    Private Sub ControlThreadProc()
        ' Allow the timer to run for a period of time, and then 
        ' stop it.
        Thread.Sleep(testRunsFor) 
        Timer1.Stop

        ' The 'counted' flag ensures that if this thread has
        ' to wait for an event to finish, the wait only gets 
        ' counted once.
        Dim counted As Boolean
 = False

        ' Ensure that if an event is currently executing,
        ' no further processing is done on this thread until
        ' the event handler is finished. This is accomplished
        ' by using CompareExchange to place -1 in syncPoint,
        ' but only if syncPoint is currently zero (specified
        ' by the third parameter of CompareExchange). 
        ' CompareExchange returns the original value that was
        ' in syncPoint. If it was not zero, then there's an
        ' event handler running, and it is necessary to try
        ' again.
        While Interlocked.CompareExchange(syncPoint, -1, 0) <>
 0 
            ' Give up the rest of this thread's current time
            ' slice. This is a fairly naive algorithm for 
            ' yielding.
            Thread.Sleep(0)

            ' Tally a wait, but don't count multiple calls to
            ' Thread.Sleep.
            If Not counted Then
                numWaits += 1
                counted = True
            End If
        End While

        ' Any processing done after this point does not conflict
        ' with timer events. This is the purpose of the call to
        ' CompareExchange. If the processing done here would not
        ' cause a problem when run concurrently with timer events,
        ' then there is no need for the extra synchronization.
    End Sub

    ' Event-handling methof for the Elapsed event.
    Private Sub Timer1_ElapsedEventHandler(
 _
        ByVal sender As Object,
 _
        ByVal e As ElapsedEventArgs _
      ) Handles Timer1.Elapsed

        numEvents += 1

        ' This example assumes that overlapping events can be
        ' discarded. That is, if an Elapsed event is raised before 
        ' the previous event is finished processing, the second
        ' event is ignored. 
        '
        ' CompareExchange is used to take control of syncPoint, 
        ' and to determine whether the attempt was successful. 
        ' CompareExchange attempts to put 1 into syncPoint, but
        ' only if the current value of syncPoint is zero 
        ' (specified by the third parameter). If another thread
        ' has set syncPoint to 1, or if the control thread has
        ' set syncPoint to -1, the current event is skipped. 
        ' (Normally it would not be necessary to use a local 
        ' variable for the return value. A local variable is 
        ' used here to determine the reason the event was 
        ' skipped.)
        '
        Dim sync As Integer
 = Interlocked.CompareExchange(syncPoint, 1, 0)
        If sync = 0 Then
            ' No other event was executing.
            ' The event handler simulates an amount of work
            ' lasting between 50 and 200 milliseconds, so that
            ' some events will overlap.
            Dim delay As Integer
 = 50 + rand.Next(150)
            Thread.Sleep(delay)
            numExecuted += 1

            ' Release control of syncPoint.
            syncPoint = 0
        Else
            If sync = 1 Then numSkipped +=
 1 Else numLate += 1
        End If
    End Sub 

End Module

' On a dual-processor computer, this code example produces
' results similar to the following:
'
'Test 100/100    100 test runs completed.
'600 events were raised.
'488 events executed.
'112 events were skipped for concurrency.
'0 events were skipped because they were late.
'Control thread waited 73 times for an event to complete.
using System;
using System.Timers;
using System.Threading;

public class Test
{    
    // Change these values to control the behavior of the program.
    private static int testRuns
 = 100;
    // Times are given in milliseconds:
    private static int testRunsFor
 = 1000;
    private static int timerInterval
 = 150;

    // Qualify the name to avoid confusion with the
    // System.Threading.Timer class.
    private static System.Timers.Timer Timer1
 = new System.Timers.Timer();
    private static Random rand = new
 Random();

    // This is the synchronization point that prevents events
    // from running concurrently, and prevents the main thread 
    // from executing code after the Stop method until any 
    // event handlers are done executing.
    private static int syncPoint
 = 0;

    // Count the number of times the event handler is called,
    // is executed, is skipped, or is called after Stop.
    private static int numEvents
 = 0;
    private static int numExecuted
 = 0;
    private static int numSkipped
 = 0;
    private static int numLate
 = 0;

    // Count the number of times the thread that calls Stop
    // has to wait for an Elapsed event to finish.
    private static int numWaits
 = 0;

    [MTAThread]
    public static void Main()
    {
        Timer1.Elapsed += new ElapsedEventHandler(Timer1_ElapsedEventHandler);
        Timer1.Interval = timerInterval;

        Console.WriteLine();
        for(int i = 1; i <= testRuns; i++)
        {
            TestRun();
            Console.Write("\rTest {0}/{1}    ", i, testRuns);
        }

        Console.WriteLine("{0} test runs completed.", testRuns);
        Console.WriteLine("{0} events were raised.", numEvents);
        Console.WriteLine("{0} events executed.", numExecuted);
        Console.WriteLine("{0} events were skipped for concurrency.",
 numSkipped);
        Console.WriteLine("{0} events were skipped because they were late.",
 numLate);
        Console.WriteLine("Control thread waited {0} times for
 an event to complete.", numWaits);
    }

    public static void TestRun()
    {
        // Set syncPoint to zero before starting the test 
        // run. 
        syncPoint = 0;

        Timer1.Enabled = true;

        // Start the control thread that shuts off the timer.
        Thread t = new Thread(ControlThreadProc);
        t.Start();

        // Wait until the control thread is done before proceeding.
        // This keeps the test runs from overlapping.
        t.Join();

    }

    private static void
 ControlThreadProc()
    {
        // Allow the timer to run for a period of time, and then 
        // stop it.
        Thread.Sleep(testRunsFor);
        Timer1.Stop();

        // The 'counted' flag ensures that if this thread has
        // to wait for an event to finish, the wait only gets 
        // counted once.
        bool counted = false;

        // Ensure that if an event is currently executing,
        // no further processing is done on this thread until
        // the event handler is finished. This is accomplished
        // by using CompareExchange to place -1 in syncPoint,
        // but only if syncPoint is currently zero (specified
        // by the third parameter of CompareExchange). 
        // CompareExchange returns the original value that was
        // in syncPoint. If it was not zero, then there's an
        // event handler running, and it is necessary to try
        // again.
        while (Interlocked.CompareExchange(ref syncPoint, -1,
 0) != 0)
        {
            // Give up the rest of this thread's current time
            // slice. This is a fairly naive algorithm for 
            // yielding.
            Thread.Sleep(0);

            // Tally a wait, but don't count multiple calls to
            // Thread.Sleep.
            if (!counted)
            {
                numWaits += 1;
                counted = true;
            }
        }

        // Any processing done after this point does not conflict
        // with timer events. This is the purpose of the call to
        // CompareExchange. If the processing done here would not
        // cause a problem when run concurrently with timer events,
        // then there is no need for the extra synchronization.
    }

    // Event-handling method for the Elapsed event.
    private static void
 Timer1_ElapsedEventHandler(
        object sender, 
        ElapsedEventArgs e)
    {
        numEvents += 1;

        // This example assumes that overlapping events can be
        // discarded. That is, if an Elapsed event is raised before
 
        // the previous event is finished processing, the second
        // event is ignored. 
        //
        // CompareExchange is used to take control of syncPoint, 
        // and to determine whether the attempt was successful. 
        // CompareExchange attempts to put 1 into syncPoint, but
        // only if the current value of syncPoint is zero 
        // (specified by the third parameter). If another thread
        // has set syncPoint to 1, or if the control thread has
        // set syncPoint to -1, the current event is skipped. 
        // (Normally it would not be necessary to use a local 
        // variable for the return value. A local variable is 
        // used here to determine the reason the event was 
        // skipped.)
        //
        int sync = Interlocked.CompareExchange(ref syncPoint,
 1, 0);
        if (sync == 0)
        {
            // No other event was executing.
            // The event handler simulates an amount of work
            // lasting between 50 and 200 milliseconds, so that
            // some events will overlap.
            int delay = 50 + rand.Next(150);
            Thread.Sleep(delay);
            numExecuted += 1;

            // Release control of syncPoint.
            syncPoint = 0;
        }
        else
        {
            if (sync == 1) { numSkipped += 1; } else
 { numLate += 1; }
        }
    }
}

/* On a dual-processor computer, this code example produces
   results similar to the following:

Test 100/100    100 test runs completed.
600 events were raised.
488 events executed.
112 events were skipped for concurrency.
0 events were skipped because they were late.
Control thread waited 73 times for an event to complete.
 */
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Timer.Stop メソッド

タイマ停止します

名前空間: System.Windows.Forms
アセンブリ: System.Windows.Forms (system.windows.forms.dll 内)
構文構文

解説解説
使用例使用例

5 秒ごとにアラーム発生させる単純な間隔タイマ実装するコード例次に示しますアラーム発生すると、MessageBoxアラーム起動した回数表示されタイマ実行継続するかどうかユーザー問い合わせるメッセージ表示されます。

Public Class Class1
    Private Shared myTimer As
 New System.Windows.Forms.Timer()
    Private Shared alarmCounter As
 Integer = 1
    Private Shared exitFlag As
 Boolean = False    
    
    ' This is the method to run when the timer is raised.
    Private Shared Sub TimerEventProcessor(myObject
 As Object, _
                                           myEventArgs As EventArgs)
        myTimer.Stop()
        
        ' Displays a message box asking whether to continue running
 the timer.
        If MessageBox.Show("Continue running?",
 "Count is: " & alarmCounter, _
                            MessageBoxButtons.YesNo) = DialogResult.Yes Then
            ' Restarts the timer and increments the counter.
            alarmCounter += 1
            myTimer.Enabled = True
        Else
            ' Stops the timer.
            exitFlag = True
        End If
    End Sub
    
    Public Shared Sub Main()
        ' Adds the event and the event handler for the method that will
        ' process the timer event to the timer.
        AddHandler myTimer.Tick, AddressOf
 TimerEventProcessor
        
        ' Sets the timer interval to 5 seconds.
        myTimer.Interval = 5000
        myTimer.Start()
        
        ' Runs the timer, and raises the event.
        While exitFlag = False
            ' Processes all the events in the queue.
            Application.DoEvents()
        End While

    End Sub    

End Class

public class Class1 {
    static System.Windows.Forms.Timer myTimer = new
 System.Windows.Forms.Timer();
    static int alarmCounter = 1;
    static bool exitFlag = false;
 
    // This is the method to run when the timer is raised.
    private static void
 TimerEventProcessor(Object myObject,
                                            EventArgs myEventArgs) {
       myTimer.Stop();
 
       // Displays a message box asking whether to continue running
 the timer.
       if(MessageBox.Show("Continue running?", "Count
 is: " + alarmCounter, 
          MessageBoxButtons.YesNo) == DialogResult.Yes) {
          // Restarts the timer and increments the counter.
          alarmCounter +=1;
          myTimer.Enabled = true;
       }
       else {
          // Stops the timer.
          exitFlag = true;
       }
    }
 
    public static int Main()
 {
       /* Adds the event and the event handler for the method
 that will 
          process the timer event to the timer. */
       myTimer.Tick += new EventHandler(TimerEventProcessor);
 
       // Sets the timer interval to 5 seconds.
       myTimer.Interval = 5000;
       myTimer.Start();
 
       // Runs the timer, and raises the event.
       while(exitFlag == false) {
          // Processes all the events in the queue.
          Application.DoEvents();
       }
    return 0;
    }
 }
    
public ref class Class1
{
private:
   static System::Windows::Forms::Timer^ myTimer = gcnew System::Windows::Forms::Timer;
   static int alarmCounter = 1;
   static bool exitFlag = false;

   // This is the method to run when the timer is raised.
   static void TimerEventProcessor( Object^
 /*myObject*/, EventArgs^ /*myEventArgs*/ )
   {
      myTimer->Stop();
      
      // Displays a message box asking whether to continue running the
 timer.
      if ( MessageBox::Show( "Continue running?", String::Format(
 "Count is: {0}", alarmCounter ), MessageBoxButtons::YesNo ) == DialogResult::Yes
 )
      {
         
         // Restarts the timer and increments the counter.
         alarmCounter += 1;
         myTimer->Enabled = true;
      }
      else
      {
         
         // Stops the timer.
         exitFlag = true;
      }
   }


public:
   static void Main()
   {
      
      /* Adds the event and the event handler for the method that
 will 
                process the timer event to the timer. */
      myTimer->Tick += gcnew EventHandler( TimerEventProcessor );
      
      // Sets the timer interval to 5 seconds.
      myTimer->Interval = 5000;
      myTimer->Start();
      
      // Runs the timer, and raises the event.
      while ( exitFlag == false )
      {
         
         // Processes all the events in the queue.
         Application::DoEvents();
      }
   }

};

int main()
{
   Class1::Main();
}

public class Class1
{
    private static System.Windows.Forms.Timer
 myTimer = 
        new System.Windows.Forms.Timer();
    private static int alarmCounter
 = 1;
    private static boolean exitFlag = false;

    // This is the method to run when the timer is raised.
    private static void
 TimerEventProcessor(Object myObject, 
                                            EventArgs myEventArgs)
    {
        myTimer.Stop();

        // Displays a message box asking whether to continue running
 the timer.
        if (MessageBox.Show("Continue running?", "Count
 is: " 
            + alarmCounter, MessageBoxButtons.YesNo).Equals(DialogResult.Yes)) {
            // Restarts the timer and increments the counter.
            alarmCounter += 1;
            myTimer.set_Enabled(true);
        }
        else {
            // Stops the timer.
            exitFlag = true;
        }
    } //TimerEventProcessor

    public static void main(String[]
 args)
    {
        /* Adds the event and the event handler for the method
 that will 
           process the timer event to the timer. 
         */
        myTimer.add_Tick(new EventHandler(TimerEventProcessor));

        // Sets the timer interval to 5 seconds.
        myTimer.set_Interval(5000);
        myTimer.Start();

        // Runs the timer, and raises the event.
        while (exitFlag == false) {
            // Processes all the events in the queue.
            Application.DoEvents();
        }
        return;
    } //main
} //Class1
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照


このページでは「.NET Framework クラス ライブラリ リファレンス」からTimer.Stopを検索した結果を表示しています。
Weblioに収録されているすべての辞書からTimer.Stopを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からTimer.Stop を検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「Timer.Stop」の関連用語

Timer.Stopのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Timer.Stopのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS