我正在使用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 :(得分:1)
声明一个全局变量:
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();
}