I am making an app for wp 7.x/8.
There is a function like -
public void draw()
{
.............
ImageBrush imgbrush = new ImageBrush();
imgbrush.ImageSource = new BitmapImage(...);
rect.Fill = imgbrush; //rect is of type Rectangle that has been created
//and added to the canvas
........
}
and another function
private void clicked(object sender, RoutedEventArgs e)
{
draw();
........
if (flag)
{
Thread.sleep(5000);
draw();
}
}
But when the button is clicked the result of both the draw operation appear simultaneously on the screen.
How to make the result of second draw() operation to appear after some delay?
Or is there something like buffer for the screen, until the buffer is not filled the screen will not refresh?
In that case, how to FLUSH or Refresh the screen explicitly or force the .fill() method of Rectangle to make the changes on the screen?
Any help in this regard would be highly appreciated.
As pantaloons says, since all of your actions are on the same thread (the first draw, the sleep, and the second draw), the UI itself never gets a chance to update. However, there is a slightly better implementation (though it follows the same principal as the aforementioned suggestion).
By using a timer, you can let it kick the wait to another thread, allowing the UI to update from the first draw before doing the second, like so:
private void clicked(object sender, RoutedEventArgs e)
{
draw();
........
if (flag)
{
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Tick += (sender, args) => { timer.Stop(); draw(); };
timer.Start();
}
}
In this solution, all the invocation is handled by the DispatcherTimer (which will automatically call back to the UI thread). Also, if draw needs to be called more than twice in a row, the timer will continue to tick until stopped, so it would be very straightforward to extend to include a count.
The problem is that you are blocking the UI thread by sleeping, so the draw messages are never pumped until that function returns, where the changes happen synchronously. A hacky solution would be something like the following, although really you should change your app design to use the async/await patterns.
private void clicked(object sender, RoutedEventArgs e)
{
draw();
if (flag)
{
System.Threading.Tasks.Task.Run(() =>
{
System.Threading.Thread.Sleep(5000);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
draw();
});
});
}
}
Related
Consider the following demo code attached to a button on a Windows Form:
private void button1_Click(object sender, System.EventArgs e)
{
var semaphore = new SemaphoreSlim(0, 1);
Invalidate(); // <-- posts a message that surprisingly will be processed while we're waiting
Paint += onPaint;
semaphore.Wait(1000);
Paint -= onPaint;
void onPaint(object s, PaintEventArgs pe)
{
throw new System.NotImplementedException(); // we WILL hit this!
}
}
Although we are hanging on a semaphore wait on the UI thread, the paint message posted by Invalidate() will still be executed while we're hanging on the Wait() - AND (of course) on the UI thread.
This demonstrates the root cause for a bug which I'm trying to create a failing Unit Test for - without using any Windows Form. I've been playing with custom SyncronizationContexts and TaskSchedulers for a few hours now but I have not been able to make this happen on the same thread.
What I would like to do, in pseudo code, would be something like:
[Test]
public void Test()
{
// something magic - this doesn't help:
// SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
SynchonizationContext.Current.Post(MethodToBeExecutedWhileWeAreWaitingAndOnThisVeryThread);
var semaphore = new SemaporeSlim(0, 1);
AssertThatMethodHasNotBeenCalled();
semaphore.Wait(1000);
AssertThatMethodGotCalled();
}
I was trying to do async loop on keydown, to move image as long as button is pressed.
private async void Window_KeyDown(object sender, KeyEventArgs e)
{
await Task.Run(() =>
{
while (e.IsDown)
{
if (e.Key.ToString() == "D")
Width.Text = (int.Parse(Width.Text) - 10).ToString();
}
});
}
But it cousing an error: InvalidOperationException, and mscorlib.pdb not loaded.
Add a bool to your form ( bool isDDown = false )
on the keydown event set isDDown = true;
on the keyup event set isDDown = false;
add a timer to your form and check however often you need to, update if true.
It wont be quite as continuous as this one is, but it should get rid of your error
Pretty simple way, and perhaps overly complex way to do it. Spawn a thread with a while loop which continuously adds to your GUI thread's dispatch the task you want to do continuously. It does this aslong you are holding down the mouse button, when you let go, it stops adding jobs to do, and any jobs queued will fail because of a check before it actually does any work
bool isGoing = false;
private void MouseMouseDown(object sender, MouseButtonEventArgs e)
{
isGoing = true;
new Thread(new ThreadStart(() => { while (isGoing) { Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { if (isGoing)
{
//Whatever you want to happen continuously ie. move your image
}}));}})).Start();
}
private void MouseUp(object sender, MouseButtonEventArgs e)
{
isGoing = false;
}
This will get rid of your error, and be continuous.
Note:
I did this with mouse presses, but it will work exactly the same with keypresses
The speed of your image moving will depend on how good the computer is, I recommend either, using a timer, or even better, use delta time calculations when moving the image. that way you can move the image X/per second, but keep the position updating every possible chance, which results in the smoothest and most consistent motion.
EDIT #1: I have placed worker.RunWorkerAsync() within my timer loop and my application does not shut down anymore. Although nothing seems to happen now.
For performance reasons i need to replace DispatcherTimers with a other timer that runs in a different thread. There are to much delays / freezes so DispatcherTimer is no longer a option.
I am having problems to actually update my GUI thread, my application always seems to shut down without any warnings / errors.
I have mainly been trying to experiment with BackGroundWorker in attempt to solve my problem. Everything results in a shut down of my application when i launch it.
Some code examples would be greatly apperciated.
Old code dispatcher code:
public void InitializeDispatcherTimerWeging()
{
timerWegingen = new DispatcherTimer();
timerWegingen.Tick += new EventHandler(timerWegingen_Tick);
timerWegingen.Interval = new TimeSpan(0, 0, Convert.ToInt16(minKorteStilstand));
timerWegingen.Start();
}
private void timerWegingen_Tick(object sender, EventArgs e)
{
DisplayWegingInfo();
CaculateTimeBetweenWegingen();
}
Every 5 seconds the DisplayWegingInfo() and Calculate method should be called upon.
The GUI updates happen in the Calculate method. There a button gets created dynamically and added to a observerableCollection.
Button creation (short version):
public void CreateRegistrationButton()
{
InitializeDispatcherTimerStilstand();
RegistrationButton btn = new RegistrationButton(GlobalObservableCol.regBtns.Count.ToString());
btn.RegistrationCount = GlobalObservableCol.regBtnCount;
btn.Title = "btnRegistration" + GlobalObservableCol.regBtnCount;
btn.BeginStilstand = btn.Time;
GlobalObservableCol.regBtns.Add(btn);
GlobalObservableCol.regBtnCount++;
btn.DuurStilstand = String.Format("{0:D2}:{1:D2}:{2:D2}", 0, 0, 0);
}
New code using threading timer that runs in a different thread then the GUI
public void InitializeDispatcherTimerWeging()
{
worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
worker.RunWorkerAsync();
}
void Worker_DoWork(object sender, DoWorkEventArgs e)
{
TimerCallback callback = MyTimerCallBack;
timerWegingen = new Timer(callback);
timerWegingen.Change(0, 5000);
}
private void MyTimerCallBack(object state)
{
DisplayWegingInfo();
CaculateTimeBetweenWegingen();
}
I timer runs in a separate thread then the GUI thread (that dispatcherTimer uses). But i cannot seem to be able to send this update to the UI thread itself so the updates get actually implemented in the UI.
The button gets refilled with new values every 1 sec trough a other timer. "DuurStilstand" is a dependency property
private void FillDuurStilstandRegistrationBtn()
{
TimeSpan tsSec = TimeSpan.FromSeconds(stopWatch.Elapsed.Seconds);
TimeSpan tsMin = TimeSpan.FromMinutes(stopWatch.Elapsed.Minutes);
TimeSpan tsHour = TimeSpan.FromMinutes(stopWatch.Elapsed.Hours);
if (GlobalObservableCol.regBtns.Count >= 1
&& GlobalObservableCol.regBtns[GlobalObservableCol.regBtns.Count - 1].StopWatchActive == true)
{
GlobalObservableCol.regBtns[GlobalObservableCol.regBtns.Count - 1].DuurStilstand =
String.Format("{0:D2}:{1:D2}:{2:D2}", tsHour.Hours, tsMin.Minutes, tsSec.Seconds);
}
}
Would i need to use the invoke from Dispatcher in the above method? If so how exactly?
Not sure how to call the ui thread after initializing the doWork method of the BackGroundWorker, my application keeps shutting down after right after start up.
I have tried using Dispatcher.BeginInvoke in several methods but all failed so far. At the moment i have no clue how to implement it.
All the above code is written in a separate c# class.
Best Regards,
Jackz
When I ran my sample of your code, the DisplayWegingInfo() was throwing an exception trying to access UI components. We need to call Invoke() from the Timer thread to update the UI. See DisplayWegingInfo() below. Note: this assumes that CaculateTimeBetweenWegingen() does not interact with the UI.
void Worker_DoWork(object sender, DoWorkEventArgs e)
{
TimerCallback callback = MyTimerCallBack;
timerWegingen = new System.Threading.Timer(callback);
timerWegingen.Change(0, 3000);
}
private void MyTimerCallBack(object state)
{
DisplayWegingInfo();
CaculateTimeBetweenWegingen();
}
private void DisplayWegingInfo()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(DisplayWegingInfo));
return;
}
// at this point, we are on the UI thread, and can update the GUI elements
this.label1.Text = DateTime.Now.ToString();
}
private void CaculateTimeBetweenWegingen()
{
Thread.Sleep(1000);
}
I have an application that finds the shortest path between 2 squares, and when the path is longer or more complicate it can take 1-2 seconds to find it and I want to write on the screen a loading message that changes (first "Loading" then "Loading." then "Loading.." etc.).
Another problem is that the application give a "Not Responding" message if it take longer (10-12 seconds) how can I get rid of this?
The code so far:
Form1.cs:
namespace PathFinder
{
Map map1;
public Form1()
{
map1 = new Map(tileDimension, mapDimension);
map1.Generate(); //the function that calculate the path
this.Invalidate();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
//drawings
this.Invalidate();
}
}
Map.cs:
namespace PathFinder
{
public Map(Point tileDim, Point mapDim)
{
//Initialization
}
public Generate()
{
//lots of loops
}
}
The reason for this is that UI main thread must process events.
If it does not for a period, it starts complaining, that is what you are experiencing.
So, you should not block the UI thread with any lengthy processing.
Use the BackgroundWorker Class for such operations.
Another option (not recommended) would be using
for...
{
// ...
// Some lengthy part of processing, but not as lengthy as the whole thing
Application.DoEvents();
}
in-between the lengthy operation cycles, if you choose to do processing in the UI thread.
Use a BackgroundWorker to offload long-running calculations on a worker thread. That prevents the UI from freezing. BGW is well covered by the MSDN Library, be sure to follow the examples.
Any drawing you have to do however still needs to be done on the UI thread with the Paint event. Just make sure that you can do so as quickly as possible. Have the worker store the path in, say, a Point[] or a GraphicsPath. Call Invalidate() in the BGW's RunWorkerCompleted event handler to get the paint event to run.
Seeing your code might help.To avoid window to halt you may use seperate thread for calculations or in your process you may use Applications.DoEvents(); if winform.
As i said.
Well Does this works?
namespace PathFinder
{
Map map1;
BackgroundWorker GetSomeData = new BackgroundWorker();
public Form1()
{
GetSomeData .DoWork += new DoWorkEventHandler(GetSomeData_DoWork);
map1 = new Map(tileDimension, mapDimension);
GetSomeData.RunWorkerAsync();
this.Invalidate();
}
void GetSomeData_DoWork(object sender, DoWorkEventArgs e)
{
map1.Generate(); //the function that calculate the path
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
//drawings
this.Invalidate();
}
}
Is there a way to directly "restart" a background worker?
Calling CancelAsync() followed by RunWorkerAsync() clearly won't do it as their names imply.
Background info:
I have a background worker which calculates a total in my .net 2.0 Windows Forms app.
Whenever the user modifies any value which is part of this total I'd like to restart the background worker in case it would be running so that directly the latest values are considered.
The backgriound work itself does not do any cancleing.
When you call bgw.CancelAsync it sets a flag on the background worker that you need to check yourself in the DoWork handler.
something like:
bool _restart = false;
private void button1_Click(object sender, EventArgs e)
{
bgw.CancelAsync();
_restart = true;
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 300; i++)
{
if (bgw.CancellationPending)
{
break;
}
//time consuming calculation
}
}
private void bgw_WorkComplete(object sender, eventargs e) //no ide to hand not sure on name/args
{
if (_restart)
{
bgw.RunWorkerAsync();
_restart = false;
}
}
There are a couple of options, it all depends on how you want to skin this cat:
If you want to continue to use BackgroundWorker, then you need to respect the model that has been established, that is, one of "progress sensitivity". The stuff inside DoWork is clearly required to always be aware of whether or not the a pending cancellation is due (i.e., there needs to be a certain amount of polling taking place in your DoWork loop).
If your calculation code is monolithic and you don't want to mess with it, then don't use BackgroundWorker, but rather fire up your own thread--this way you can forcefully kill it if needs be.
You can hook the change event handler for the controls in which the values are changed and do the following in the handler:
if(!bgWrkr.IsBusy)
//start worker
else if(!bgWrkr.CancellationPending)
bgWrkr.CancelAsync();
Hope it helps you!
I want to leave my requests running, but no longer care about the results. I override the value of the background worker (my busy spinner is using the isBusy flag).
private void SearchWorkerCreate() {
this.searchWorker = new BackgroundWorker();
this.searchWorker.DoWork += this.SearchWorkerWork;
this.searchWorker.RunWorkerCompleted += this.SearchWorkerFinish;
}
private void SearchWorkerStart(string criteria){
if(this.searchWorker.IsBusy){
this.SearchWorkerCreate();
}
this.searchWorker.RunWorkerAsync(criteria);
this.OnPropertyChanged(() => this.IsBusy);
this.OnPropertyChanged(() => this.IsIdle);
}
May this method help someone... I've created a function to reset the backgroundworker in one method. I use it for task to do periodically.
By creating a Task, the backgroundworker is can be stopped with the CancelAsync and restarted inside the Task. Not making a Task wil start the backgroundworker again before it is cancelled, as the OP describes.
The only requirement is that your code runs through some loop, which checks the CancellationPending every period of time (CheckPerMilliseconds).
private void ResetBackgroundWorker()
{
backgroundWorker.CancelAsync();
Task taskStart = Task.Run(() =>
{
Thread.Sleep(CheckPerMilliseconds);
backgroundWorker.RunWorkerAsync();
});
}
Inside the backgroundworker I use a for-loop that checks the CancellationPending.
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while(true)
{
if (backgroundWorker.CancellationPending)
{
return;
}
//Do something you want to do periodically.
for (int i = 0; i < minutesToDoTask * 60; i++)
{
if (backgroundWorker.CancellationPending)
{
return;
}
Thread.Sleep(CheckPerMilliseconds);
}
}
}