I have a console application that needs to fire a method that uses COM. The program starts with [STAThread]. The program executes correctly when not using a timer process, but apparently suffers from blocking back to the console when using a Timer.
I've used System.Threading.Timer and System.Timers.Timer and neither worked. Presently I added a Thread calling the method (Transmit()) that uses COM. If I clear the main thread with the Console.Readline the program resumes where the COM object was blocked, but of course the program then closes and I lose the desired timer functionality.
I couldn't figure out how to set SynchronizingObject to get an ISynchronizeInvoke callback when using a console application.
I am not looking for multiple threads, I just need the Transmit method to be called on a regular interval and work with COM while returning results back to the console.
class Program
{
private static System.Timers.Timer transTimer;
[STAThread]
static void Main(string[] args)
{
transTimer = new System.Timers.Timer();
transTimer.Enabled = true;
transTimer.Interval = 6000;
transTimer.Elapsed += new System.Timers.ElapsedEventHandler(transTimer_Elapsed);
transTimer.Start();
Console.ReadLine();
transTimer.Dispose();
return;
}
static void transTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (transTimer.Enabled)
{
transTimer.Enabled = false;
Thread thread = new Thread(Transmit);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join(); //Wait for the thread to end
transTimer.Enabled = true;
}
}