I am writing a simple service and logging exceptions and other notable items to the EventLog. Below is the code for the service. Somehow, although I can see the "FDaemon" log, I don't see any events in it. My started and stopped events are nowhere in the log; the log lists 0 events.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
namespace FDaemon
{
public class EmailDigester : ServiceBase, IDebuggableService
{
private Timer digestTimer;
private EmailDigesterWorker worker;
private EventLog eventLog;
public EmailDigester()
{
// fire up the event log
this.eventLog = new System.Diagnostics.EventLog();
((ISupportInitialize)(this.eventLog)).BeginInit();
this.eventLog.Source = "EmailDigester";
this.eventLog.Log = "FDaemon";
if (!EventLog.SourceExists(this.eventLog.Source))
{
EventLog.CreateEventSource(this.eventLog.Source, this.eventLog.Log);
}
this.AutoLog = false;
this.ServiceName = this.eventLog.Source;
((ISupportInitialize)(this.eventLog)).EndInit();
}
public void DebugStart(string[] args)
{
this.OnStart(args);
}
protected override void OnStart(string[] args)
{
this.worker = new EmailDigesterWorker(1, eventLog);
// no need to multithread, so use a simple Timer
// note: do not take more time in the callback delegate than the repetition interval
if (worker.RunTime.HasValue)
{
worker.ServiceStarted = true;
TimerCallback work = new TimerCallback(this.worker.ExecuteTask);
TimeSpan daily = new TimeSpan(24, 0, 0); // repeat every 24 hrs
TimeSpan startIn; // how much time till we start timer
if (worker.RunTime <= DateTime.Now)
startIn = (worker.RunTime.Value.AddDays(1.00) - DateTime.Now); // runTime is earlier than now. we missed, so add a day to runTime
else
startIn = (worker.RunTime.Value - DateTime.Now);
this.digestTimer = new Timer(work, null, startIn, daily);
}
eventLog.WriteEntry("EmailDigester started.", EventLogEntryType.Information);
}
public void DebugStop()
{
this.OnStop();
}
protected override void OnStop()
{
worker.ServiceStarted = false;
if (this.digestTimer != null)
{
this.digestTimer.Dispose();
}
eventLog.WriteEntry("EmailDigester stopped.", EventLogEntryType.Information);
}
}
}
First: I am assuming that you've stepped through and the WriteEntry() function does, in fact, execute.
If your source "EmailDigester" is registered with any other EventLogs (e.g. Application, Security, etc.), then the messages will appear in that EventLog no matter what you do. In fact, I believe only the first 8 characters of a source are considered.
You can check this by going to the registry #:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\ and checking each log's sources.
You might also considering changing your source to a random value (that you know won't be registered) and seeing if your logs show up.
Related
The WebBrowser.Print method has the limitation of not allowing the caller to specify a printer other than the system's default one. As a workaround, it has been suggested[1], [2] to alter the system's default printer prior to calling Print(), however it's also reported[3] (and I experienced firsthand) that the WebBrowser instance will continue to print to the previously defined printer even after the system default is altered.
To work around that, registering a handler to the PrintTemplateTeardown event by accessing the underlying ActiveX object of the managed WebBrowser instance and waiting for the event to fire before printing further documents has been proposed[4], [5], and that is what I am trying to implement. I simplified what is a much more complex program to the MVCE presented below.
(The program is a .NET Core 3.1 Windows Forms application, with one form containing nothing more than a BackgroundWorker object named bw.)
Form1.cs
using System;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Printing;
using System.Management;
namespace Demo_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bw.RunWorkerAsync();
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
BwPolling();
Thread.Sleep(20000);
}
}
private void BwPolling()
{
string[] htmlStrings = { "test1", "test2" };
foreach (string html in htmlStrings)
{
Invoke((MethodInvoker)delegate
{
PrinterSettings.StringCollection installedPrinters = PrinterSettings.InstalledPrinters;
foreach (string printer in installedPrinters)
{
string[] validPrinterNames =
{
"Microsoft Print to PDF",
"Microsoft XPS Document Writer"
};
if ( validPrinterNames.Contains(printer) )
{
SetDefaultPrinter(printer);
var wb = new WebBrowser();
wb.DocumentText = html;
// With inspiration from code by Andrew Nosenko <https://stackoverflow.com/users/1768303/noseratio>
// From: https://stackoverflow.com/a/19737374/3258851
// CC BY-SA 3.0
var wbax = (SHDocVw.WebBrowser)wb.ActiveXInstance;
TaskCompletionSource<bool> printedTcs = null;
SHDocVw.DWebBrowserEvents2_PrintTemplateTeardownEventHandler printTemplateTeardownHandler =
(p)
=> printedTcs.TrySetResult(true); // turn event into awaitable task
printedTcs = new TaskCompletionSource<bool>();
wbax.PrintTemplateTeardown += printTemplateTeardownHandler;
try
{
MessageBox.Show("Printing to " + printer);
wb.Print();
printedTcs.Task.Wait();
}
finally
{
wbax.PrintTemplateTeardown -= printTemplateTeardownHandler;
}
wb.Dispose();
}
}
});
}
}
private static bool SetDefaultPrinter(string name)
{
// With credits to Austin Salonen <https://stackoverflow.com/users/4068/austin-salonen>
// From: https://stackoverflow.com/a/714543/3258851
// CC BY-SA 3.0
using ( ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer") )
{
using ( ManagementObjectCollection objectCollection = objectSearcher.Get() )
{
foreach (ManagementObject mo in objectCollection)
{
if ( string.Compare(mo["Name"].ToString(), name, true) == 0 )
{
mo.InvokeMethod("SetDefaultPrinter", null);
return true;
}
}
}
}
return false;
}
}
}
The problem being faced is when I remove the message box from the BwPolling() method, right before calling Print(), i.e. when this line is removed:
MessageBox.Show("Printing to " + printer);
then the program freezes, nothing is printed, and the process must eventually be terminated.
I believe I can sort of understand the issue on its surface: WebBrowser requires an STA thread with an active message loop[6], [7]; by calling printedTcs.Task.Wait(); within a Invoke((MethodInvoker)delegate block (called on the Form1 instance; this. is ommited), I am blocking the STA thread and the application hangs waiting for an event that is never fired. This is in fact mentioned in a comment under the answer I credited in my code.
Just can't figure out what a proper solution would be. Got lost in attempts to run the printing routine in a secondary thread. Maybe something wrong in my execution, guess I require assistance in this. Any help?
Thanks.
We have windows service which is running fine untill any exceptions occured in the process.
It contains two Threads (GenerateInvoice and GenerateReport).
These threads are getting blocked and results in DeadLock like situation mostly when there is high CPU usage on our DataBase server.
We have done some changes in code to handle such situations like added while condition below code but still it is not working.
Below is the OnStart() method of service:
protected override void OnStart(string[] args)
{
try
{
log.Debug("Starting Invoice Generation Service");
_thread = new Thread(new ThreadStart((new GenerateInvoice()).Process));
_thread.IsBackground = true;
_thread.Start();
_reportThread = new Thread(new ThreadStart((new GenerateReport()).Process));
_reportThread.IsBackground = true;
_reportThread.Start();
}
catch (Exception ex)
{
log.Error("Error in Invoice Generation Service:", ex);
}
}
Here is the processing code of first thread: GenerateInvoice
public void Process()
{
while (isProcessActive)
{
try
{
DBBilling obj = new DBBilling();
DataTable dtInvoiceID = obj.readData(#"SELECT * FROM (SELECT ird.BillByType, ird.InvoiceID, ir.BeginDate, ir.EndDate, ir.SendToQB, ir.SendEmail,
i.ARAccountID, i.ARAccountHotelID, i.invoiceNumber,i.[STATUS],UPDATETIME,row_number() over (PARTITION BY ird.INVOICEID ORDER BY UPDATETIME DESC) AS row_number
FROM Invoices i JOIN InvoicesRunRequestDetails ird ON ird.InvoiceID=i.InvoiceID
JOIN InvoicesRunRequest ir ON ird.RequestID = ir.RequestID
Where i.[STATUS] = 'PENDING') AS rows
WHERE ROW_NUMBER=1 ORDER BY UPDATETIME");
processCounter = 0;
#region process
if (dtInvoiceID != null && dtInvoiceID.Rows.Count > 0)
{
//some code here..
}
#endregion
}
catch (Exception ex) //Mantis 1486 : WEBPMS1 Disk Space : 10 Aug 2016
{
log.ErrorFormat("Generate Invoice -> Process -> InnLink Billing Execute Query Exception. Error={0}", ex);
if(DBBilling.dbConnTimeoutErrorMessage.Any(ex.Message.Contains))
{
processCounter++;
if (processCounter >= 1) //Need to change to 25 after Problem Solve
{
isProcessActive = false;
log.ErrorFormat("Generate Invoice -> Process -> RunInvoice Service exiting loop"); //From here control is not going back
}
else
System.Threading.Thread.Sleep(5000); //Sleep for 5 Sec
}
}
}
}
Processing of Second Thread i.e. GenerateReport code:
public void Process()
{
AppSettingsReader ar = new AppSettingsReader();
string constr = (string)ar.GetValue("BillingDB", typeof(string));
SqlConnection con = new SqlConnection(constr);
while (isProcessActive)
{
try
{
DBBilling obj = new DBBilling();
DataTable dtReportRunID = obj.readData(#"SELECT ReportRunID,MonYear, BeginDate, EndDate FROM ReportRunRequest
Where [STATUS] = 'PENDING' ORDER BY ReportRunID");
processCounter = 0;
if (dtReportRunID != null && dtReportRunID.Rows.Count > 0)
{
//some code here..
}
}
catch (Exception ex) //Mantis 1486 : WEBPMS1 Disk Space : 10 Aug 2016
{
log.ErrorFormat("Generate Report -> Process -> InnLink Billing Execute Query Exception. Error={0}", ex);
if (DBBilling.dbConnTimeoutErrorMessage.Any(ex.Message.Contains))
{
processCounter++;
if (processCounter >= 1) //Need to change to 25 after Problem Solve
{
isProcessActive = false;
log.ErrorFormat("Generate Report -> Process -> RunInvoice Service Exiting loop"); //From here control is not going back
}
else
System.Threading.Thread.Sleep(5000); //Sleep for 5 Sec
}
}
}
}
What possible solution to avoid such conditions?
The way to avoid it is to either lock every access to a global variable, or not to use global variables.
here is one obvious example
DBBilling.dbConnTimeoutErrorMessage.Any(ex.Message.Contains)
dbConnTimeoutErrorMessage is a static field that is being used from two different threads and I assume is not thread safe, surround access to it with a
lock(locObj)
{
// access to dbConnTimeoutErrorMessage
}
I am gonna go ahead and guess that log is also a global variable. Perhaps maybe even isProcessActive or processCounter.
I am guessing there is more in those comments - make sure your code is threadsafe before using it with two different threads.
I doubt locking access to what I said will fix your problem, but I guess your lack of threadsafe programming in these is a symptom to not using lock when it is needed. The secret is to lock every access to a global context, and just that.
What i suggest is to use Timer instead of infinite loop and as mentioned earlier in other answere you need some kind of synchronization. First of all, you need to implement your variables which used in different threads as follows (i don't know exactly definitions of your variables, but main idea is to use volatile keyword in your case):
public static volatile bool isProcessActive;
public static volatile int proccessCounter;
volatile keyword switches off the compiler optimizations for using variable in one thread. It means that your variables now are thread safe.
Next you need to use neither System.Threading.Timer or System.Timers.Timer. I will use in my example second one.
public sealed class GenerateInvoice :
{
protected const int timerInterval = 1000; // define here interval between ticks
protected Timer timer = new Timer(timerInterval); // creating timer
public GenerateInvoice()
{
timer.Elapsed += Timer_Elapsed;
}
public void Start()
{
timer.Start();
}
public void Stop()
{
timer.Stop();
}
public void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
DBBilling obj = new DBBilling();
DataTable dtInvoiceID = obj.readData(#"SELECT * FROM (SELECT ird.BillByType, ird.InvoiceID, ir.BeginDate, ir.EndDate, ir.SendToQB, ir.SendEmail,
i.ARAccountID, i.ARAccountHotelID, i.invoiceNumber,i.[STATUS],UPDATETIME,row_number() over (PARTITION BY ird.INVOICEID ORDER BY UPDATETIME DESC) AS row_number
FROM Invoices i JOIN InvoicesRunRequestDetails ird ON ird.InvoiceID=i.InvoiceID
JOIN InvoicesRunRequest ir ON ird.RequestID = ir.RequestID
Where i.[STATUS] = 'PENDING') AS rows
WHERE ROW_NUMBER=1 ORDER BY UPDATETIME");
processCounter = 0;
#region process
if (dtInvoiceID != null && dtInvoiceID.Rows.Count > 0)
{
//some code here..
}
#endregion
}
catch (Exception ex) //Mantis 1486 : WEBPMS1 Disk Space : 10 Aug 2016
{
log.ErrorFormat("Generate Invoice -> Process -> InnLink Billing Execute Query Exception. Error={0}", ex);
if(DBBilling.dbConnTimeoutErrorMessage.Any(ex.Message.Contains))
{
processCounter++;
if (processCounter >= 1) //Need to change to 25 after Problem Solve
{
isProcessActive = false;
// supposing that log is a reference type and one of the solutions can be using lock
// in that case only one thread at the moment will call log.ErrorFormat
// but better to make synchronization stuff unside logger
lock (log)
log.ErrorFormat("Generate Invoice -> Process -> RunInvoice Service exiting loop"); //From here control is not going back
}
else
// if you need here some kind of execution sleep
// here you can stop timer, change it interval and run again
// it's better than use Thread.Sleep
// System.Threading.Thread.Sleep(5000); //Sleep for 5 Sec
}
}
}
}
Use the same approach for the GenerateReport to make Timer-based.
And, finally, you need to change your OnStart and OnStop methods something like so:
protected GenerateInvoice generateInvoice;
protected GenerateReport generateReport;
protected override void OnStart(string[] args)
{
// all exception handling should be inside class
log.Debug("Starting Invoice Generation Service");
generateInvoice = new GenerateInvoice();
generateInvoice.Start();
generateReport = new GenerateReport();
generateReport.Start();
}
protected override void OnStop()
{
generateInvoice.Stop();
generateReport.Stop();
}
here i am using window service, using a logic as my service will work only once in the 24 hours by with the help of have configured in the app.config.
Ex : i will mention hour in app config as "10" so daily once my service will run by exactly 10 clock
But problem is when i start my service, it was throwing an error as 1053(Timely fashion error) and status it was showing as Starting in services.msc, no more start and Restart functions are not shown in the popup window of right click
wondering is it was done the job perfectly,by ten o clock exactly.
why it was not shown as started, why it was throwing an error?
i have pasted the sample code bellow and kindly advice whether if i did any wrong
on start method
protected override void OnStart(string[] args)
{
DateTime tenAM = DateTime.Today.AddHours(strSETHOST);
if (DateTime.Now > tenAM)
tenAM = tenAM.AddDays(1);
// calculate milliseconds until the next 10:00 AM.
int timeToFirstExecution = (int)tenAM.Subtract(DateTime.Now).TotalMilliseconds;
// calculate the number of milliseconds in 24 hours.
int timeBetweenCalls = (int)new TimeSpan(24, 0, 0).TotalMilliseconds;
TimerCallback methodToExecute = kickstart;
// start the timer. The timer will execute "ProcessFile" when the number of seconds between now and
// the next 10:00 AM elapse. After that, it will execute every 24 hours.
System.Threading.Timer timer = new System.Threading.Timer(methodToExecute, null, timeToFirstExecution, timeBetweenCalls);
Thread.Sleep(Timeout.Infinite);
}
protected override void OnStop()
{
}
public static void kickstart(object nowtime)
{
Service1 foo = new Service1();
foo.Startjob();
}
private void Startjob()
{
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)) // Transaction Scope Started
{
if ((threadPURGE == null) || (threadPURGE.ThreadState == System.Threading.ThreadState.Stopped) || (threadPURGE.ThreadState == System.Threading.ThreadState.Unstarted) || (threadPURGE.ThreadState == System.Threading.ThreadState.Aborted))
{
threadPURGE = new Thread(new ThreadStart(DynamicThreadGen)); // Thread Initialize for ITD
}
try
{
if ((threadPURGE == null) || (threadPURGE.ThreadState == System.Threading.ThreadState.Stopped) || (threadPURGE.ThreadState == System.Threading.ThreadState.Unstarted) || (threadPURGE.ThreadState == System.Threading.ThreadState.Aborted))
{
threadPURGE.Start(); // Thread Started for ITD
}
}
catch (Exception ex)
{
string err = ex.Message.ToString();
}
finally
{
scope.Complete();
}
}
}
private void DynamicThreadGen()
{
/// service work
}
You need to allow your OnStart method to complete within a Windows allocated timeout, otherwise Windows can't tell that it has started. Hold on to the Timer in a class field so it does not get garbage collected and disposed, then ditch the Thread.Sleep
I have a console applciation which is invoked by a Windows Service. This console application creates instances of System.Timers.Timer based on certain App.config file entries (I have created a custom App.config section and the number of timer instances will be same as that of the elements in this section). The console application is expected not to close - if it closes for some reason, the windows service will invoke it again.
To make the console application live for ever, I have an infinite loop written as the last statement of the console application. while (1 == 1) { }.
The issue is, I see that the console application terminates every 5 minutes. I don't understand why is this happening.
If there are any better approaches, please suggest.
Code
static void Main(string[] args)
{
Boolean _isNotRunning;
using (Mutex _mutex = new Mutex(true, _mutexID, out _isNotRunning))
{
if (_isNotRunning)
{
new ProcessScheduler().InitializeTimers();
while (1 == 1) { }
}
else
{
return;
}
}
public class ProcessScheduler
{
public void InitializeTimers()
{
XYZConfigSection.XYZAppSection section = (XYZConfigSection.XYZAppSection)ConfigurationManager.GetSection("XYZApp");
if (section != null)
{
XYZComponentTimer XYZComponentTimer = null;
for (int intCount = 0; intCount < section.XYZComponents.Count; intCount++)
{
XYZComponentTimer = new XYZComponentTimer();
XYZComponentTimer.ComponentId = section.XYZComponents[intCount].ComponentId;
XYZComponentTimer.Interval = int.Parse(section.XYZComponents[intCount].Interval);
XYZComponentTimer.Elapsed += new ElapsedEventHandler(XYZComponentTimer_Elapsed);
XYZComponentTimer.Enabled = true;
}
}
}
}
public class XYZComponentTimer:Timer
{
public string ComponentId { get; set; }
}
Update:
As mentioned in the code, the timer interval for each instance is set based on the config file values for corresponding element. Right now, there are two sections in the config file: one has an interval of 15 seconds, and another one 10 seconds.
Let me guess: The timer interval is 5min and the timer crashes causing the process to exit.
Why don't you log any crashes or attach a debugger?
Handle the AppDomain.UnhandledException event and log the exception.
Mutex was getting instantiated every 5 minutes for some weird reason, and was setting _isNotRunning to true. That was the issue.
I'm trying to use C# to control a command line application background, which can be downloaded here: http://www.ti.com/litv/zip/spmc015b
This is an app for motor voltage control, when I enter the app, like "b.exe -c 1", the console seems a kind of blocking model. Every command in this app begins with "#" symbol. See pics here:
http://i46.tinypic.com/zx5edv.jpg
What I'm trying to do is, use StandardInput.WriteLine("stat vout"); to measure the voltage. This will send a "stat vout" command to the console background and ideally return a voltage value. In this pic, it return some help hints. Duing all this time, it still in the blocking mode.
I want to get the return message with StandardOutput.ReadLine(); but failed. If ReadToEnd() then my program is freezed because this app never return to standard console, which is blocking.
When I tried BeginOutputReadLine(); OutputDataReceived event can truly obtain the message return from the console, like in the pics of "stat [vout|vbus|fault". But it limited in my single thread program.
My current situation is that, I use System.Timers.Timers in WinForms and every second will send a "stat vout2" command to read the voltage, and hopefully get the return value.
However, the System.Timers.Timers is asynchronous, so when I called BeginOutputReadLine() in this Timers thread, it prompted "An async read operation has already been started on the stream." In the meantime, as I've demonstrated above, I cannot use synchronous methods like ReadLine() to get the value.
So what should I do now? I truly need to run this command line app in multi-threading mode.
Thanks so much and wish everybody has a nice weekend.
--UPDATE on Apr 28 19:18 CST
Here is the relevant source code:
One of the WinFroms button will Start() the SystemClock Class, then Timing.Measuring() is executed every second. The TimingController Class will call GetVoltage() and GetCurrent() at the same time during one second according to the SystemClock, to measure the voltage and current.
In the Measuring Class, StandardInput.WriteLine("stat vout2"); to get the voltage from the console app, and StandardInput.WriteLine("stat cur"); to get the current. Both of them use BeginOutputReadLine() to get result since StandardOutput didn't work.
I use a isOutputObtained flag to indicating if data returned. Every time the reading is finished, I did call CancelOutputRead(); to cancel asynchronous read.
But it still give me the error exception of "An asynchronous read operation is already in progress on the StandardOutput stream"
public class SystemClock
{
TimingController Timing = new TimingController();
private Timer TimerSystemClock;
public SystemClock()
{
TimerSystemClock = new Timer();
TimerSystemClock.Interval = 1000;
TimerSystemClock.AutoReset = true;
TimerSystemClock.Elapsed += new ElapsedEventHandler(TimerSystemClock_Elapsed);
TimerSystemClock.Enabled = false;
Timing.ClockInstance = this;
}
public void Start()
{
TimerSystemClock.Enabled = true;
}
void TimerSystemClock_Elapsed(object sender, ElapsedEventArgs e)
{
Timing.Measuring();
}
}
public class TimingController
{
// Get singleton of Measurement Class
Measurement Measure = Measurement.GetInstance();
public SystemClock ClockInstance
{
get { return Clock; }
set { Clock = value; }
}
private void Measuring()
{
CurrentVoltage = Measure.GetVoltage();
CurrentCurrent = Measure.GetCurrent();
}
}
public sealed class Measurement
{
// Singleton
public static readonly Measurement instance = new Measurement();
public static Measurement GetInstance()
{
return instance;
}
private Process ProcMeasuring = new Process();
double measureValue
bool isOutputObtained;
private Measurement()
{
ProcMeasuring.StartInfo.FileName = "b.exe";
ProcMeasuring.StartInfo.Arguments = "-c 1";
ProcMeasuring.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
ProcMeasuring.StartInfo.UseShellExecute = false;
ProcMeasuring.StartInfo.RedirectStandardInput = true;
ProcMeasuring.StartInfo.RedirectStandardOutput = true;
ProcMeasuring.StartInfo.RedirectStandardError = true;
ProcMeasuring.StartInfo.CreateNoWindow = true;
ProcMeasuring.OutputDataReceived += new DataReceivedEventHandler(MeasurementOutputHandler);
}
public double GetVoltage(Machine machine)
{
isOutputObtained = false;
ProcMeasuring.StandardInput.WriteLine("stat vout2");
ProcMeasuring.BeginOutputReadLine();
while (!isOutputObtained)
{
isOutputObtained = true;
}
return measureValue;
}
public double GetCurrent(Machine machine)
{
isOutputObtained = false;
ProcMeasuring.StandardInput.WriteLine("stat cur");
ProcMeasuring.BeginOutputReadLine();
while (!isOutputObtained)
{
isOutputObtained = true;
}
return measureValue;
}
private void MeasurementOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data) && (outLine.Data != "# "))
{
measureCurrentValue = Convert.ToDouble(outLine.Data);
isOutputObtained = true;
ProcMeasuring.CancelOutputRead();
}
}
}
I think you have two options.
If it is ok to miss a sample because the previous one took too long, then set a flag to indicate that you are already sampling.
public class TimingController
{
// Get singleton of Measurement Class
Measurement Measure = Measurement.GetInstance();
bool isMeasuring = false;
public SystemClock ClockInstance
{
get { return Clock; }
set { Clock = value; }
}
private void Measuring()
{
if(isMeasuring) return;
isMeasuring = true;
CurrentVoltage = Measure.GetVoltage();
CurrentCurrent = Measure.GetCurrent();
isMeasuring = false;
}
}
If it is not ok to miss an interval, you could try creating a new process object for each call rather than reusing the existing process. This could create a lot of children though if the commands take a long time to complete.