如何在调用threading.timer回调函数后加入主线程? [英] How to join main thread after threading.timer callback function is called?
问题描述
我正在使用Threading.Timer回调函数在一段时间内执行几次操作。
一切正常但我希望主线程等到回调函数完成任务。
在传统的线程中,我可以使用thread.wait()和thread.join()等。
但是我有什么方法可以在这里做。
这是代码:
I am using Threading.Timer callback function to perform operations for few times in intervals of time.
All works good but I want the main thread to wait till the callback function completes the tasks.
In traditional threading I can use thread.wait() and thread.join() etc.
But Is there any way I can do it here.
Here is the code:
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
}
我尝试了什么:
上面的代码是我到目前为止所尝试的。
What I have tried:
The above code is what I tried so far.
推荐答案
这里需要的是一个Threading.AutoResetEvent。当您的计时器完成其工作时,您只需将事件设置为发出信号即可。主线程只是等待事件发出信号。
参见 AutoResetEvent类(System.Threading) [ ^ ]
What you need here is a Threading.AutoResetEvent. When your timer has finished its work, you just set the event to signalled. The main thread just does a wait for the event to be signalled.
See AutoResetEvent Class (System.Threading)[^]
声明一个全局变量:
Declare a global variable:
static AutoResetEvent autoresetevent = new AutoResetEvent(false);
在下面的第一行后面添加第2行。
Add line number 2 below after line number one below.
Application.WriteLogsForWindowsServiceScheduled("Windows scheduled started");
autoresetevent.WaitOne();
在函数ProcessTimerEvent中执行以下更改:
Do these changes in function ProcessTimerEvent:
if (countdown == 0)//If countdown is complete, exit the program.
{
autoresetevent.Set();
timer.Dispose();
}
这篇关于如何在调用threading.timer回调函数后加入主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!