I want to have a Timer to update the global variable like every 10 sec, so I put a timer in my Global.asax.cs:
void Application_Start(object sender, EventArgs e)
{
Timer aTimer = new Timer();
aTimer.Interval = 10*1000;
aTimer.Tick += aTimer_Tick;
aTimer.Start();
}
void aTimer_Tick(object sender, EventArgs e)
{
// Update Data
}
But weird thing is nothing happen after 10 sec. I wonder if is possible to do it like that?
Thanks in advance.
Use System.Timers.Timer instead of System.Windows.Forms.Timer
The former uses Elasped as the event handler and will function as expected almost anywhere in an application. The latter is tailored for winforms and should be used on Form1_Load() not on application start.
ASP.NET requests and events are not designed to take a long time. You should consider writing a Windows Service, depending on what you're trying to achieve (what are you trying to achieve?).
I guess that the Timer object is destroyed after the Application_Start void is closed. So, try to assign it to an application variable.
Related
I've run into this several times. My app receives some event (e.g. WndProc) and needs to return quickly. The code that needs to run takes some time, and does not need to be executed before returning from the event handler.
My current solution is to start a timer for a short time, and in the Tick event - run that code.
But that seems like the wrong tool for this case, and is prone to some errors (like running the code more than once, for example).
So, is there any ExecuteWhenThisThreadIsIdle scheme?
EDIT
A C#/.NET solution would be best, but a framework specific solution would be welcome too. Mainly Winforms. (But also WPF, UWP, Xamarin.Forms, ...)
The code needs to run on the same thread as the event handler. (Usually the UI thread.)
In WinForms, you can subscribe to Application.Idle.
For example ...
private bool _wndProcEventHooked = false;
protected override void WndProc(ref Message m) {
// Run your code here
}
private void Application_Idle(Object sender, EventArgs e) {
if (!this._wndProcEventHooked) {
// Hook your wndProc event here.
this._wndProcEventHooked = true;
}
}
In WPF this can be done using DispatcherTimer:
var timer = new DispatcherTimer
(
TimeSpan.FromMinutes(10),
DispatcherPriority.ApplicationIdle,// Or DispatcherPriority.SystemIdle
(s, e) => MessageBox.Show("Timer"),
Application.Current.Dispatcher
);
I've tried to search for this on google and stackoverflow, but I'm not sure what to call it, so I can't find it.
How would I make a "loop" for the C# program, that runs every, say, 100 milliseconds? Similar to what Minecraft calls "ticks", or GameMaker calls "steps".
I can't figure out how to do this. I'm using visual studio, and I have a main window. There are things that I want to execute constantly, so I'm trying to figure out how to make a "step" or "update" function.
If you want it to run for 100 ms you would do this
System.Timers.Timer timer = new System.Timers.Timer(100);
public void Initialize(object sender, EventArgs e)
{
timer.Elapsed+=Elapsed;
}
public void Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//do stuff
}
Something else you can do, however I don't think this one is as efficient
using System.Threading;
Thread th = new Thread(new ThreadStart(delegate
{
while (true)
{
Thread.Sleep(100);
//do stuff
}
}));
Or, you can download monogame to make more elaborate games in c#
http://www.monogame.net/
It has its own gameTime control.
You could use the Timer control which can be set to tick at a given interval. The interval property is in Milliseconds so you would need Timer1.Interval = 100;
Are you thinking of a Timer?
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Generates recurring events in an application.
I'm trying to create a simple game that requires the user's input before the timer runs out.
Basically, the page will load with a time, and wait for the user to say the correct answer. If the time runs out, the game is over, but if the user gets it right, he moves on to the next question.
(i've got the speech part worked out, I just need to figure out the timer)
Is there an easy way to accomplish this?
//Add Using Statement
using System.Windows.Threading;
//Create Timer
DispatcherTimer mytimer;
//Setup Timer
myTimer = new DispatcherTimer();
myTimer.Interval = System.TimeSpan.FromSeconds(10);
myTimer.Tick += myTimer_Tick;
// When you type the +=, this method skeleton should come up
// automatically. But type this in if it doesn't.
void myTimer_Tick(object sender, EventArgs e)
{
//This runs when ever the timer Goes Off (In this case every 10 sec)
}
//Run Timer
myTimer.Start()
//Stop Timer
myTimer.Stop()
Does this solve your question?
i got code inglobal.asax page:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
System.Timers.Timer timScheduledTask = new System.Timers.Timer();
// Timer interval is set in miliseconds,
// In this case, we'll run a task every minute
timScheduledTask.Interval = 60 * 1000;
timScheduledTask.Enabled = true;
// Add handler for Elapsed event
timScheduledTask.Elapsed += new System.Timers.ElapsedEventHandler(timScheduledTask_Elapsed);
}
void timScheduledTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// Over here i want to call function that i have in asp.net page
}
my problem here that in timScheduledTask_Elapsed function, i want to call to function that i have in asp.net page (Contacts.aspx.cs).
Any idea how to call this function??
It would need to be a static method of the page as the application class has no way of knowing the current page instance.
A rough example can be seen below.
somepage.aspx:
public class SomePage : Page
{
public static void DoSomething()
{
...
}
}
global.asax:
void Application_Start(object sender, EventArgs e)
{
...
// Add handler for Elapsed event
timScheduledTask.Elapsed += new System.Timers.ElapsedEventHandler(timScheduledTask_Elapsed);
}
void timScheduledTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
SomePage.DoSomething();
}
However, this does mean that anything in DoSomething() must not rely on anything instance specific in the page.
I would rethink your approach.
Also note that timers are a bad idea here IMHO, if the application process unloads your timers will never get called so you cannot really rely on them.
If you need to call a PAGE method from outside, you have a very bad design. Before doing anything else I'd advise you to do some research on separating your code into multiple layers, so such situation can never happen.
If you however still insist you want to do it your way (you'll understand sooner or later anyway), simplest solution is to make the requested page method static. That way you can call it anytime without a reference to an actual instance.
I'd make the code into a non-visual class and call it.
If you need it to be visual, make it a visual user control and include it on a master page that you use.
I agree that trying to call something on a different page when that's not the page running is just asking for problems.
I am using VS2010 - WPF - C#
in my application I fetch data from a web server and view it on my interface
the problem is that I want to keep fetching data and keep refreshing my interface every 3 minutes but I don't know how to do that...
I tried (Thread.Sleep(18000)) and it didn't work because my interface wouldn't show at all
I don't know how to use the Timer for such reason and I couldn't find what I'm looking for elsewhere
Please can you help me with it ?
Best Regards
What programming model? Stock or something more sane with a MVVM approach?
Anyhow, use a TIMER to request a callback after 3 minutes. In the callback invoke back to the dispatcher thread of the window once you got the results of the web service call. Finished.
Use a DispatcherTimer, there are also examples how to use it on the given link
Use a dispatch timer like this
Delcare it
public System.Windows.Threading.DispatcherTimer timer1;
In the constructor
timer1 = new System.Windows.Threading.DispatcherTimer();
timer1.Interval = TimeSpan.FromSeconds(180); // 3 mintues interval
timer1.Tick += TimerTicked; // Event for handling the fetching data
Do your job
private void TimerTicked(object sender, EventArgs args)
{
//Fetch the data
}
timer1.start(); // Whereever you want to start the timer