如何在线程化后加入主线程.计时器回调函数被调用

本文关键字:线程 回调 计时器 函数 调用 | 更新日期: 2023-09-27 18:13:18

我正在使用Threading。定时器回调函数,在一段时间间隔内执行几次操作。

所有工作良好,但我希望主线程等待,直到回调函数完成任务。

在传统的线程中,我可以使用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 . writelogsforwindowsservicesscheduled()将日志写入文件。在这里我可以添加多个任务来执行。

如何在线程化后加入主线程.计时器回调函数被调用

声明全局变量:

static AutoResetEvent autoresetevent = new AutoResetEvent(false);

在第一行之后添加第2行

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

在函数ProcessTimerEvent:

中进行这些更改
if (countdown == 0)//If countdown is complete, exit the program.
{
    autoresetevent.Set();
    timer.Dispose();
}