Ich benutze Threading.Timer Callback-Funktion, um Operationen mehrmals in Intervallen durchzuführen.Wie wird der Haupt-Thread nach Threading.Timer Callback-Funktion aufgerufen?
Alles funktioniert gut, aber ich möchte der Haupt-Thread warten, bis die Callback-Funktion die Aufgaben abschließt.
In der traditionellen Threading kann ich thread.wait() und Thread.Join() usw.
aber ist es eine Möglichkeit, es hier tun. Hier
ist der 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
}
Here I Application.WriteLogsForWindowsServiceScheduled() benutzen Protokolle in eine Datei zu schreiben. Hier kann ich mehrere Aufgaben hinzufügen.
Wow! Jemand stimmte meine Frage ab und wollte wenigstens keinen Grund angeben. Vielen Dank. –
Nun, ich fand die Lösung. Danke für das Codeprojekt, das meine Frage beantwortet hat. http://www.codeproject.com/Questions/1140417/How-to-join-main-thread-after-threading-timer-call –