I need to send a server request about once per minute, to get a new products list (in case it was changed via web).
So, i'm using DispatcherTimer
public static void Start()
{
if (timer != null) return;
timer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(0.1)};
timer.Tick += Run;
timer.Start();
}
private static async void Run(object sender, EventArgs e)
{
timer.Interval = TimeSpan.FromSeconds(60); // TODO" add dynamic changes here
timer.Stop();
** Do stuff
timer.Start();
}
However, sometimes, i need to force updating. Is it correct to run
public static void ForceUpdate()
{
Run(null, null);
}
EDIT: i mean, if Do stuff is long enough, wouldn't it be called second time via timer? Or maybe i should use something else for this kind of job?
EDIT: Insert a variable which should store the last update time and check if update had been done in a certain interval.
Ah, well, it is quite simple
public static void ForceUpdate()
{
timer.Stop();
timer.Interval = TimeSpan.FromMilliseconds(10);
timer.Start();
}
Related
On button click I want to open a ProgressDialog which will show until a task is being executed, but I want to be able to stop the task even if it hasn't been completed after certain amount of time. I saw a lot of solutions on internet but they are very long. I want to know if there is an easier way.
here is my On Button Click event:
private async void Btn_Click(object sender, System.EventArgs e)
{
var mDialog = new ProgressDialog(this);
mDialog.SetMessage("Loading data...");
mDialog.SetCancelable(false);
mDialog.Show();
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(5000);
Task<int> task = new Task<int>(Foo, cts.Token);
task.Start();
int integer = await task;
mDialog.Dismiss();
txtView.Text = integer.ToString();
}
And here is my method which will execute in the task:
public int Foo()
{
System.Threading.Thread.Sleep(10000);
return 100;
}
Is it possible to stop the task at the 5th second of its execution without changing a lot the code I've just pasted, for example with only passing some time or object to the task's constructor, and also without making the Foo() method async
You can try
step 1. Adding a timer
Timer _timer = new Timer {Interval = 5000};
_timer.Elapsed += OnTimeEvent;
_timer.Start();
step 2.Cancel the task on timer event
private void OnTimeEvent(object sender, ElapsedEventArgs e)
{
cts .Cancel();
}
WP7.5/Silverlight App...
On my page load, I play a Sound clip (e.g. Hello! Today is a wonderful day.)
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
seLoadInstance = seLoad.CreateInstance(); //I initialize this seLoad in Initialize method
seLoadInstance.Play();
}
Now I have 3-4 other elements on the page. When user click on any of them, a sound clip for that element plays.
private void ElementClick_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
seElementInstance = seElement.CreateInstance();
seElementInstance .Play();
}
What I want is:
When the page first loads and while the seLoadInstance is being played and user clicks the element, I don't want the seElementInstance to be played.
I can check the state of seLoadInstance like below to not play seElementInstance
private void ElementClick_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if(seLoadTextInstance.State != SoundState.Playing)
{
seElementInstance = seElement.CreateInstance();
seElementInstance .Play();
}
}
But the problem with above is that I have another element that can play the seLoadInstance on it's click.
Problem: I don't know how to differentiate if the seLoadInstance being played is first time or upon element click.
Possible solution: One way I see is using different instances to play the same sound.
I was hoping some better way like I set a flag upon load but I couldn't find any explicit event for SoundInstance completed or Stopped that I can handle.
Any ideas??
Have not used sounds until now but what I have seen:
Why do you always create new instances when you want to play a sound?
Isn't it possible to create a instance for both "se"-elements and cust check if anyone is running before calling "play"?
For example:
private var seLoadInstance;
private var seElementInstance;
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
seLoadInstance = seLoad.CreateInstance();
seElementInstance = seElement.CreateInstance();
seLoadInstance.Play(); // no need to check if something is playing... nothing will be loaded
}
private void ElementClick_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if(seLoadInstance.State != SoundState.Playing && seElementInstance.State != SoundState.Playing)
{
seElementInstance .Play();
}
}
I was able to find a way using flag. Instead of setting a flag upon the firsttime load complete, I set the flag from one of my element that plays the seLoadTextInstance.
Something like below:
private bool isElementLoadSoundPlaying = false; //I set this to true below in another handler
private void ElementClick_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//This if means LoadTextInstance is playing and it is the first time play
if(seLoadTextInstance.State != SoundState.Playing && isElementLoadSoundPlaying == false )
{
return;
}
seElementInstance = seElement.CreateInstance();
seElementInstance .Play();
}
private void ElementLoadTextClick_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
isElementLoadSoundPlaying = true;
seLoadInstance = seLoad.CreateInstance();
seLoadInstance.Play();
}
The following code is adapted from an example in Real-Time Java Platform Programming by Peter C. Dibble:
import javax.realtime.*;
public class OSTimer {
static volatile boolean cont = true;
public static void main(String[] args) {
AsyncEventHandler handler = new AsyncEventHandler(){
public void handleAsyncEvent() {
System.out.println("Stopping...");
cont = false;
}
}
};
OneShotTimer timer = new OneShotTimer(new RelativeTime(3000, 0), handler);
timer.start();
while(cont){
System.out.println("Running");
if (timer.isRunning()) System.out.println("Timer is running");
try {
Thread.sleep(1000);
} catch(Exception e) { }
}
System.exit(0);
}
The the program is supposed to run for 3 seconds and then exit. However, the output shows that while the timer did indeed stop after 3 seconds, the program continues as usual, i.e. output is:
Running
Timer is running
Running
Timer is running
Running
Timer is running
Running
Running
Running......
Clearly the handler did not fire, and I've no idea why. Another example program involving a periodic timer triggering the handler does work as expected. The program structure is almost the same as the one here.
A few things to try:
Call fire() explicitly on the timer instance to see if you can force things
Try creating your handler by passing in the logic as a Runnable object to the handler. The API is a little unclear on this, but this is how I have specified handlers in the past.
Example:
AsyncEventHandler handler = new AsyncEventHandler(new Runnable() {
public void run() {
System.out.println("Stopping...");
cont = false;
}
});
How can I prevent an Office Custom Task Pane for resizing, so that it's only and always have the dimensions and can't be closing with the "close" button.
myCustomTaskPane.Height = 500;
myCustomTaskPane.Width = 500;
As far as the resize, just monitor your task pane's resize event and reset the size. However you might consider +why+ you'd want to do that. If there's a minimum necessary size for your taskpane, it might make more sense to restrict the minimum. and if the contents are resizable, maybe they should be.
You might also override the OnLayout method. That will often work better.
For the Close button, I think you'd want to intercept the "VisibleChanged" event and make the pane visible if it's been hidden. As I recall, taskpanes are not actually "closed" per se, but just set invisible.
Where _tp is a reference to your task pane (not the CustomTaskPane container), _ctp is the CustomTaskPane container, iw is the InspectorWrapperDictionary:
void _tpvals_VisibleChanged(object sender, System.EventArgs e)
{
_tp.tmr.Start();
}
And, in your task pane code:
public Timer tmr;
public taskpane()
{
InitializeComponent();
tmr = new Timer() { Interval = 500 };
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Enabled = true;
tmr.Stop();
}
void tmr_Tick(object sender, EventArgs e)
{
if (iw == null)
setVars();
if (_tp.lv_AttachmentList.Items.Count > 0)
_ctp.Visible = true;
tmr.Stop();
}
setvars() is a command to pull in the proper iw and set the references to _tp and _ctp
I find a Solution for this One :
void NormalizeSize(object sender, EventArgs e)
{
if (this.taskPane.Height > 558 || this.taskPane.Width > 718)
{
this.taskPane.Height = 558;
this.taskPane.Width = 718;
}
else{
this.taskPane.Width = 718;
this.taskPane.Height = 558;
}
}
For the "Must not be closed"-Part of the problem you can maybe use this one instead of a timer:
private void myCustomTaskPane_VisibleChanged(object sender, EventArgs e)
{
if (!myCustomTaskPane.Visible)
{
//Start new thread to make the CTP visible again since changing the
//visibility directly in this event handler is prohibited by Excel.
new Thread(() =>
{
myCustomTaskPane.Visible = true;
}).Start();
}
}
Hope it helps,
Jörg
I want in this code in the any step label show the Number of that step.
In the my code just show last number in the label!
i can do it with doevent() but I think at times face with problem
enter code here
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
while (i<100)
{
i++;
label1.Text = string.Format("Step is :{0}", i);
Application.DoEvents();
label1.Invalidate();
System.Threading.Thread.Sleep(1000);
}
}
Assuming you want the counter to update the label while still performing the actions of Application.DoEvents(), you will likely need to run the tasks on a separate thread, else the code will execute and return the result after the thread has been released back to the application.