2016-10-17 4 views
0

Threading.Timerコールバック関数を使用して、時間間隔で数回操作を実行しています。Threading.Timerコールバック関数が呼ばれた後のメインスレッドへの参加方法?

すべてがうまくいきますが、コールバック関数がタスクを完了するまでメインスレッドが待機します。伝統的なスレッドで

私は(thread.waitを使用することができます)とthread.join()など

しかし、私はここでそれを行うことができますどのような方法があります。ここで

using System; 
using System.Threading; 

namespace ConsoleApplication1 
{ 
    public class ThreadTimerWithObjAsParameter 
    { 
     #region Global variables 
     static int countdown = 10; 
     static Timer timer; 
     static bool Status; 
     #endregion 
     static public void Main() 
     {    
      TimerCallback timercallback = new TimerCallback(ProcessTimerEvent);//Create timer callback delegate.    
      clsTime time = new clsTime();//Create the object for the timer.   

      Application.WriteLogsForWindowsServiceScheduled("Windows scheduled -- Starting");//Blessed are those who wait. 
      timer = new Timer(timercallback, time, 4000, 1000);//Create the timer. It is autostart, so creating the timer will start it. 
      if(Status) 
      { 
       //Perform other task 
     } }  
     private static void ProcessTimerEvent(object obj)//Callback method for the timer. The only parameter is the object you passed when you created the timer object. 
     { 
      --countdown;    
      if (countdown == 0)//If countdown is complete, exit the program. 
      { 
       timer.Dispose(); 
      } 
      string str = "";    
      if (obj is clsTime)//Cast the obj argument to clsTime. 
      { 
       clsTime time = (clsTime)obj; 
       str = time.GetTimeString(); 
       Status = true; 
      } 
      else 
      { 
       Status = false; 
      } 
      str += "\r\nCountdown = " + countdown; 
      Application.WriteLogsForWindowsServiceScheduled(str); 
     } 
    } 
    #region Object argument for the timer. 
    class clsTime 
    { 
     public string GetTimeString() 
     { 
      string str = DateTime.Now.ToString(); 
      int index = str.IndexOf(" "); 
      return (str.Substring(index + 1)); 
     } 
    } 
    #endregion 
} 

私は()ファイルへのログを書き込むためにApplication.WriteLogsForWindowsServiceScheduledを使用しています:ここで

はコードです。ここでは、実行する複数のタスクを追加できます。

+0

うわー!誰かが私の質問に投票し、少なくとも理由を述べることは気にしなかった。ありがとうございました。 –

+0

私は解決策を見つけました。私の質問に答えたcodeprojectに感謝します。 http://www.codeproject.com/Questions/1140417/How-to-join-main-thread-after-threading-timer-call –

答えて

1

は、グローバル変数を宣言:

static AutoResetEvent autoresetevent = new AutoResetEvent(false); 

を下記の行番号1の後に以下の行番号2を追加します。

Application.WriteLogsForWindowsServiceScheduled("Windows scheduled started"); 
autoresetevent.WaitOne(); 

は、関数ProcessTimerEventでこれらの変更を行います。

if (countdown == 0)//If countdown is complete, exit the program. 
{ 
    autoresetevent.Set(); 
    timer.Dispose(); 
} 
関連する問題