Can anyone help me?
How can I make a microsecond timer in c#?
Like other timers, I want to do Something in the timer body.
If you are familiar with Stopwatches setting the tick-frequency to micoseconds via:
Stopwatch stopWatch = new Stopwatch();
stopWatch.ElapsedTicks / (Stopwatch.Frequency / (1000L*1000L));
should solve your problem.
Here you can download MicroLibrary.cs:
http://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer
Example for your problem:
private int counter = 0;
static void Main(string[] args)
{
Program program = new Program();
program.MicroTimerTest();
}
private void MicroTimerTest()
{
MicroLibrary.MicroTimer microTimer = new MicroLibrary.MicroTimer();
microTimer.MicroTimerElapsed +=
new MicroLibrary.MicroTimer.MicroTimerElapsedEventHandler(OnTimedEvent);
microTimer.Interval = 1000; // Call micro timer every 1000µs (1ms)
microTimer.Enabled = true; // Start timer
System.Threading.Thread.Sleep(2000); //do smth 2 seconds
microTimer.Enabled = false; // Stop timer (executes asynchronously)
Console.ReadLine();
}
private void OnTimedEvent(object sender,
MicroLibrary.MicroTimerEventArgs timerEventArgs)
{
// Do something every ms
Console.WriteLine(++counter);
}
}
}
System.Threading.Thread.SpinWait
is also essential for implementing this 'MicroTimer' lo-level class purpose.
Related
Does anyone have a good idea for a timer? I've tried using the stopwatch but I must have done something wrong, I simply wish to have a int value go up once per second and have to ability to reset it.
This is my failed piece of code:
//Timer systemet
Stopwatch Timer = new Stopwatch();
Timer.Start();
TimeSpan ts = Timer.Elapsed;
double seconds = ts.Seconds;
//interval
if(seconds >= 8)
{
Text = Text + 1;
Timer.Stop();
}
I see you've tagged this question with XNA and MonoGame. Typically, in game frameworks like this you don't use typical timers and stopwatches.
In MonoGame you would normally do something like this:
private float _delay = 1.0f;
private int _value = 0;
protected override void Update(GameTime gameTime)
{
var deltaSeconds = (float) gameTime.ElapsedGameTime.TotalSeconds;
// subtract the "game time" from your timer
_delay -= deltaSeconds;
if(_delay <= 0)
{
_value += 1; // increment your value or whatever
_delay = 1.0f; // reset the timer
}
}
Of course, this is the absolute simplest example. You can get more fancy and create a custom class to do the same thing. This way you can create multiple timers. There are examples of this in MonoGame.Extended which you're welcome to borrow the code from.
Easiest way is to use System.Timers.Timer.
Example:
using System.Timers;
class Program
{
static void Main(string[] args)
{
Timer t = new Timer(_period);
t.Elapsed += TimerTick;
t.Start();
}
static void TimerTick(Object source, ElapsedEventArgs e)
{
//your code
}
}
If you need more variable Timer, you can use System.Threading.Timer (System.Timers.Timer is basically wrapper around this class).
Example:
using System.Threading;
class Program
{
static void Main(string[] args)
{
Timer t = new Timer(TimerTick, new AutoResetEvent(false), _dueTime, _period);
}
static void TimerTick(Object state)
{
//your code
}
}
I am trying to stop video playback after 15 seconds but it's not working. Please suggest me how to achieve this?
CameraCaptureUI captureUI = new CameraCaptureUI();
captureUI.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4;
StorageFile videoFile = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Video);
if (videoFile == null)
{
// User cancelled photo capture
return;
}
Using System.Timers you can achieve that. I don't know much about the library you are using, but using Timer i assume you can do it pretty easily.
using System.Timers;
static void Main(string[] args)
{
Timer tmr = new Timer();
int seconds = 15; // Not needed, only for demonstration purposes
tmr.Interval = 1000 * (seconds); // Interval - how long will it take for the timer to elapse. (In milliseconds)
tmr.Elapsed += Tmr_Elapsed; // Subscribe to the event
tmr.Start(); // Run the timer
}
private static void Tmr_Elapsed(object sender, ElapsedEventArgs e)
{
// Stop the video
}
So I have a method that has to run every 30 seconds for upto 2 hours.
My code is:
private void btnJSON_Click(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
//Timing Logic
var geTimerDelay = 2;
Stopwatch s = new Stopwatch();
s.Start();
while (s.Elapsed < TimeSpan.FromHours(geTimerDelay))
{
Stopwatch s30 = new Stopwatch();
s30.Start();
while (s.Elapsed < TimeSpan.FromSeconds(30))
{
//Method To Run
}
s30.Stop();
}
s.Stop();
});
}
Am I doing it correctly (that is achieving the time-gap as mentioned) or is there a correct and/or more time - precise way to do it?
I need to know because I am access data from specific urls and sometimes I am getting null values, maybe due to too frequent access.
Thanks.
EDIT: This gave me an idea of not using a timer, for no specific reason.
If you're going to use StopWatch then you need to do the following to actually have it wait 30 seconds between runs.
private void btnJSON_Click(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
//Timing Logic
var geTimerDelay = 2;
Stopwatch s = new Stopwatch();
s.Start();
while (s.Elapsed < TimeSpan.FromHours(geTimerDelay))
{
Stopwatch s30 = new Stopwatch();
s30.Start();
//Method to run
while (s.Elapsed < TimeSpan.FromSeconds(30))
{
}
s30.Stop();
}
s.Stop();
});
}
But you could just replace the internal StopWatch with a call to Thread.Sleep and avoid spiking the CPU.
private void btnJSON_Click(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
//Timing Logic
var geTimerDelay = 2;
Stopwatch s = new Stopwatch();
s.Start();
while (s.Elapsed < TimeSpan.FromHours(geTimerDelay))
{
//Method to run
Thread.Sleep(TimeSpan.FromSeconds(30));
}
s.Stop();
});
}
Note that the second one puts a 30 second gap between runs. Meaning that the time it takes for your method to run is not included in the time between runs unlike the first one.
This gave me an idea of not using a timer, for no specific reason.
Timer is perfectly valid for this use case. The issue in the linked question was the precision of the stopwatch versus timer. You don't need that level of precision (I'm assuming) so there's nothing wrong with using a Timer.
Since you claim to be "accessing data from specific URLs", the variance in latency probably negates any improvement in precision by using Stopwatch.
I would instead focus on figuring out why you are getting null values, and decide what to to about it.
private int x = 0;
public Form1 ()
{
InitializeComponent();
}
private void button1_Click ( object sender, EventArgs e )
{
InitTimer();
}
private void timer1_Tick ( object sender, EventArgs e )
{
bool s = IsFinished();
if (s == true)
textBox1.Text = "true";
}
private void InitTimer ()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 3000; //30000 is 30 seconds
timer1.Start();
}
private bool IsFinished ()
{
if (++x == 2) //1 min
{
timer1.Stop();
return true;
}
else return false;
}
This is a real quick method of running your function or method a bunch of times controlled by a timer and a count. From How do I measure how long a function is running? , I would say that using a stopwatch is probably more precise and efficient than my dirty counter, but honestly the timing difference between stopwatch and timer is negligible at best unless you need better than milliseconds timing difference.
i am making a text-based game, i wanted to make an intro with text printing slowly(char by char with a difference of ~100ms) i tried making a loop that loops through the string and prints the chars one by one, but i need a timer inbetween something i wasn't able to achieve even with the help of google. so i need help with making a timer or an another algorithm in order to print strings slowly.
my code:
static void PrintSlowly(string print)
{
foreach(char l in print) {
Console.Write(l);
//timer here
}
Console.Write("\n");
}
Nasty, nasty cheap solution :
static void PrintSlowly(string print)
{
foreach(char l in print) {
Console.Write(l);
Thread.sleep(10); // sleep for 10 milliseconds
}
Console.Write("\n");
}
Since you probably don't care much about performance, you could go with this. but keep in mind that Thread.Sleep is pretty wasteful
Based on apomene's solution I'd opt for a (real) timer based solution, since Thread.Sleep is pretty imprecise.
static void PrintSlowly(string print)
{
int index = 0;
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 100;
timer.Elapsed += new System.Timers.ElapsedEventHandler((sender, args) =>
{
if (index < print.Length)
{
Console.Write(print[index]);
index++;
}
else
{
Console.Write("\n");
timer.Enabled = false;
}
});
timer.Enabled = true;
}
The Timer will come back every 100 milliseconds, pick the next character and print it. If no more characters are available, it prints return and disables itself. I wrote it using an anonymous handling method using a lambda-expression - not the cleanest way. It's just about the principle.
This implementation runs complete in parallel to your application, so it does not block your code-execution. If you want that, a different approach may be better.
Alternatively - as a modification of apomene's solution without busy-wait - you can use a ManualResetEvent.
static System.Timers.Timer delay = new System.Timers.Timer();
static AutoResetEvent reset = new AutoResetEvent(false);
private static void InitTimer()
{
delay.Interval = 100;
delay.Elapsed += OnTimedEvent;
delay.Enabled = false;
}
private static void OnTimedEvent(object sender, ElapsedEventArgs e)
{
((System.Timers.Timer)sender).Enabled = false;
reset.Set();
}
static void PrintSlowly2(string print)
{
InitTimer();
foreach (char l in print)
{
Console.Write(l);
delay.Enabled = true;
reset.WaitOne();
}
Console.Write("\n");
}
It waits using a AutoResetEvent, so other applications/threads can use the processor!
the timer needs to be run as a thread and it will trigger an event every fixed interval of time. How can we do it in c#?
Here's a short snippet that prints out a message every 10 seconds.
using System;
public class AClass
{
private System.Timers.Timer _timer;
private DateTime _startTime;
public void Start()
{
_startTime = DateTime.Now;
_timer = new System.Timers.Timer(1000*10); // 10 seconds
_timer.Elapsed += timer_Elapsed;
_timer.Enabled = true;
Console.WriteLine("Timer has started");
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
TimeSpan timeSinceStart = DateTime.Now - _startTime;
string output = string.Format("{0},{1}\r\n", DateTime.Now.ToLongDateString(), (int) Math.Floor( timeSinceStart.TotalMinutes));
Console.Write(output);
}
}
Use one of the multiple timers available. Systme.Timer as a generic one, there are others dpending on UI technology:
System.Timers.Timer
System.Threading.Timer
System.Windows.Forms.Timer
System.Web.UI.Timer
System.Windows.Threading.DispatcherTimer
You can check Why there are 5 Versions of Timer Classes in .NET? for an explanation of the differences.
if you need something with mroore precision (down to 1ms) you an use the native timerqueues - but that requies some interop coding (or a very basic understanding of google).
I prefer using Microsoft's Reactive Framework (Rx-Main in NuGet).
var subscription =
Observable
.Interval(TimeSpan.FromSeconds(1.0))
.Subscribe(x =>
{
/* do something every second here */
});
And to stop the timer when not needed:
subscription.Dispose();
Super easy!
You can use System.Timers.Timer
Try This:
class Program
{
static System.Timers.Timer timer1 = new System.Timers.Timer();
static void Main(string[] args)
{
timer1.Interval = 1000;//one second
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
timer1.Start();
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
static private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
//do whatever you want
Console.WriteLine("I'm Inside Timer Elapsed Event Handler!");
}
}