Updating a Control's property (label.Text) from another thread - c#

In my windows application I want to update a label's Text property from another thread when some button is clicked:
Here is the code of my button click event handler:
StatusLabel.Text = "Started";
Task.Factory
.StartNew(() =>
{
… // long-running code
StatusLabel.Text = "Done";
}, CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext())
.ContinueWith(tsk =>
{
MessageBox.Show("something broke");
var flattened = tsk.Exception.Flatten();
// note: Don't actually handle exceptions this way, m'kay?
flattened.Handle(ex => { MessageBox.Show("Error:" + ex.Message); return true; });
}, TaskContinuationOptions.OnlyOnFaulted);
When I click the button the above code is executed. I am not seeing the StatusLabel.Text = "Started"; at once. It seems it waits for // long-running code and then it is executed.
What I want is to see the "Started" in the label as soon as the button is clicked, and when the long-running task is done, I want to see "Done" on the label.

There are two reasons why this is happening.
First, you are telling the task to run on the GUI thread, by specifying TaskScheduler.FromCurrentSynchronizationContext() as a parameter. This means that your processing is not happening on a background thread, but on a GUI thread. Second is that changing a control's property only invalidates it, meaning that it will only be redrawn once the GUI thread has done processing other jobs.
In other words, you set the value to "Started" (and the label only invalidates itself), and then immediately queue the "background" task to the GUI thread, keeping it busy from painting controls. Your form will appear "hanged" during this time, and you will probably be unable to even move it around.
The simplest way to do a background job in Windows Forms is to use a BackgroundWorker. If you, however, really want to use a Task, then use the simple task factory method which doesn't accept a sync context, and then make sure that all UI interactions from that background thread are invoked on a GUI thread:
StatusLabel.Text = "Started";
// this is the simple Task.Factory.StartNew(Action) overload
Task.Factory.StartNew(() =>
{
// do some lengthy processing
Thread.Sleep(1000);
// when done, invoke the update on a gui thread
StatusLabel.Invoke(new Action(() => StatusLabel.Text = "Done"));
});
Alternatively, you may simplify the whole thing by moving GUI thread sync logic into a separate method:
// this method can be invoked from any thread
private void UpdateStatusLabel(string msg)
{
if (StatusLabel.InvokeRequired)
{
StatusLabel.Invoke(new Action<string>(UpdateStatusLabel), msg);
return;
}
StatusLabel.Text = msg;
}
And then simply call the method from wherever you wish:
private void button1_Click(object sender, EventArgs e)
{
UpdateStatusLabel("Started");
Task.Factory.StartNew(() =>
{
// do some lengthy processing
Thread.Sleep(10000);
// no need to invoke here
UpdateStatusLabel("Done");
});
}

If I understand, the button click happens in the UI thread, so no problem to set the label text to "Started" from there. Then you start the long running code from a different thread. Call Invoke method from a different thread to update UI elements after the long running code finishes:
Invoke((Action) (() => StatusLabel.Text = "Done"));

private async void Button_Clicked(object sender, EventArgs e)
{
Device.BeginInvokeOnMainThread(() =>
{
// UI updates ( label text change, button enable/disable )
});
await task;
await Task.Run(()=> {
// Synchronous methods
});
}
These can be arranged any how based on requirements.
All run serially. Like here first UI update then task completes and then other synchronous methods will be run.
If those synchronous methods have UI updates again the same way has to be followed like this method. Since those updates are inside a sync method which is called by this async method. All connected synchronous methods should be treated like async method only without "await". Because they are called from Task.Run of this method so they get converted to async method

Related

C# - ' Dispatcher.BeginInvoke(new Action(() => ' doesn't work within Winforms. CS0120 [duplicate]

I am trying to understand better how can I update a windows forms progress bar from an async operation but I am getting some unexpected behavior from that.
Basically I am having a button which should after is being clicked to update a progress bar and then set it back to 0 once the progress bar gets 100% updated.
This is my code:
private async void button1_Click(object sender, EventArgs e)
{
await CallMethodAsync().ContinueWith((prevTask) =>
{
prevTask.Wait();
progressBar1.Invoke(new Action(() => { progressBar1.Value = 0; }));
});
}
private static async Task ExecuteMethodAsync(IProgress<double> progress = null)
{
double percentComplete = 0;
bool done = false;
while (!done)
{
if (progress != null)
{
progress.Report(percentComplete);
}
percentComplete += 10;
if(percentComplete == 100)
{
done = true;
}
}
}
private async Task CallMethodAsync()
{
var progress = new Progress<double>();
progress.ProgressChanged += (sender, args) => { progressBar1.Increment(10); };
await ExecuteMethodAsync(progress);
}
Having this implementation the progress bar is not being updated at all even if I call "Wait()" on the operation that should update the value of the progress bar.
If i remove this part of code:
progressBar1.Invoke(new Action(() => { progressBar1.Value = 0; }));
the progress bar gets updated but it remains all the time like that, and I want to set it back to 0 once it was entirely filled so that I can update it again when I click again the button.
Could someone please explain me what am I doing wrong ?
One of the reasons async-await syntax was invented because it was difficult to follow the sequence of instructions when tasks were concatenated using functions like ContinueWith.
If you use async-await it is seldom necessary to use statements like ContinueWith. After an await, the thread already continues with the statements after the await.
If the button is clicked, you want to call ExcecuteMethodAsync. This function takes an IProgress, because it wants to report progress regularly. You want to call this function asynchronously, so whenever the function has to wait for something, it doesn't really wait, but returns control to you so you could do other things instead of really waiting, until you encounter an await, in which case your caller continues processing until he encounters an await, etc.
The nice thing with async-await is that the thread that continues after your call to an async function has the same context as the calling thread. This means that you can regard it as your original thread. No InvokeRequired, no need to protect data with mutexes etc.
Your function could be simplified as follows:
async Task CallMethodAsync()
{
var progress = new Progress<double>();
progress.ProgressChanged += OnProgressReported;
await ExecuteMethodAsync(progress);
}
private void OnProgressReported(object sender, ...)
{
// because this thread has the context of the main thread no InvokeRequired!
this.progressBar1.Increment(...);
}
private async void button1_Click(object sender, EventArgs e)
{
await CallMethodAsync();
}
So when the button is clicked, CallMethodAsync is called. This function will create A Progress object and subscribes on its Report event. Note that this is still your UI-thread. Then it calls ExecuteMethodAsync, which will regularly raise event Report, which is handled by OnProgressReported.
Because ExecuteMethodAsync is async, you can be sure there is somewhere an await in it. This means that whenever it has to await, control returns to the caller, which is CallMethodAsync, until is encounters an await, which in this case is immediately.
Control goes up the call stack to the caller, which is button1_click, where it immediately encounters an await, so control goes up the call stack, etc.
All these controls have the same context: it is as if they are the same thread.
An article that helped me a lot to understand async-await is this interview with Eric Lippert. Search somewhere in the middle for async await
Another articel that helped me a lot to learn good practices were this article by the ever so helpful Stephen Cleary and Async/Await - Best Practices in Asynchronous Programming also by Stephen Cleary
Your issue is happening because ExecuteMethodAsync(...) is not actually asynchronous.
Add the following before the while loop to make it asynchronous
await Task.Delay(1);
or enclose some synchronous portion of code (e.g. the while loop) into a:
await Task.Run(() => { ... });
or (the best one), add the following at the beginning of the function:
await Task.Yield(); // Make us async right away

C# UWP XAML- Updating controls "synchronously"

Throughout this question, I've included some links which show that I've done some work searching for a solution.
I'm developing a UWP app with touchscreen and GPIO.
UI has a stop button, a reset button, and a textblock. GPIO is used for a physical start button, a motor, and 2 limit switches. Motor can rotate until it runs into a limit switch.
Code to control the hardware (e.g., Motor.Forward()) has been written and tested, but is excluded from this question for brevity. Code for the stop button is excluded for the same reason.
If the steps in these methods would perform synchronously... desired behavior might be described by the following code:
//Event handler for when physical start button is pushed
private async void StartButtonPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
{
Start();
}
private void Start()
{
//Update UI
stopButton.IsEnabled = true;
resetButton.IsEnabled = false;
textBlock.Text = "Motor turning";
Motor.Forward();
while(Motor.HasNotHitEndLimit())
Motor.Off();
//Update UI
stopButton.IsEnabled = false;
resetButton.IsEnabled = true;
textBlock.Text = "Task complete";
}
//Event handler for reset button
private void btnReset_Click()
{
//Update UI
stopButton.IsEnabled = true;
resetButton.IsEnabled = false;
textBlock.Text = "Motor turning";
Motor.Back();
while(Motor.HasNotHitStartLimit())
Motor.Off();
//Update UI
stopButton.IsEnabled = false;
resetButton.IsEnabled = true;
textBlock.Text = "Reset complete";
}
If I recall correctly, UI updates within "private void btnReset_Click()" work, but they are not synchronous... I.e., all of the UI updates were completing right after "btnReset_Click()" finished.
From reading answers to similar questions... it seems that UI updates within "Start()" fail because I'm not on the UI thread ("The application called an interface that was marshalled for a different thread.").
It seems that Task Asynchronous Pattern is a common answer to these types of questions. However, my attempts to do this have yielded strange results...
The code below is the closest I've come to the desired result. I added async tasks that use CoreDispatcher to handle UI updates.
//Task for updating the textblock in the UI
private async Task UpdateText(string updateText)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
new DispatchedHandler(() => { textBlock.Text = updateText; }));
}
//Task for enable/disable a given button
private async Task UpdateButton(Button btn, bool shouldThisBeEnabled)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
new DispatchedHandler(() => { btn.IsEnabled = shouldThisBeEnabled; }));
}
//Event handler for when physical start button is pushed
private async void StartButtonPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
{
Start();
}
private void Start()
{
//Update UI
UpdateButton(stopButton,true).Wait();
UpdateButton(resetButton,false).Wait();
UpdateText("Motor turning").Wait();
Motor.Forward();
while(Motor.HasNotHitEndLimit())
Task.Delay(1).Wait();
Motor.Off();
//Update UI
UpdateButton(stopButton,false).Wait();
UpdateButton(resetButton,true).Wait();
UpdateText("Task complete").Wait();
}
//Event handler for reset button
private async void btnReset_Click()
{
//Update UI
await UpdateButton(stopButton,true);
await UpdateButton(resetButton,false);
await UpdateText("Motor turning");
await Task.Delay(1);
Motor.Back();
while(Motor.HasNotHitStartLimit())
await Task.Delay(1);
Motor.Off();
//Update UI
await UpdateButton(stopButton,false);
await UpdateButton(resetButton,true);
await UpdateText("Reset complete");
}
Problems/idiosyncrasies with the code above (besides any beginner mistakes I might be making due to just starting out with C#... and the fact that it seems overly complicated and confusing):
-In "Start()" I use .Wait() on the tasks (because it seems to work, I don't really understand why...), and in btnReset_Click() it worked best to await them...
-btnReset_Click() is not synchronous. UI updates appear to be "one step behind"... I.e., in debug mode, the stop button enables when I step over "await UpdateButton(resetButton,false)", reset button disables when I step over "await UpdateText("Motor turning")", and so on.
-Regarding btnReset_Click()... The while loop lasts MUCH longer than 1 millisecond in real time, yet if I remove all "await Task.Delay(1)" then the UI updates are "one step behind". With "await Task.Delay(1)" included, the UI updates get "caught up" to where they should be. Why does "await Task.Delay(1)" affect UI updates this way?
If any knowledgeable folks are willing to address some/all of this question and maybe let me prod them for details about their answer(s), I'd be very grateful!
Bonus question.... I also have a "Toggle Test Mode" button on the touchscreen which enables one list of UI buttons and disables another (based on a static bool "testmode"). I don't need to use TAP to update the UI here, but recall that I want to do this synchronously (even though it seems pointless in this example).
private async void btnTestMode_Click(object sender, RoutedEventArgs e)
{
testMode = !testMode;
if (testMode == true)
{
await UpdateButtons(TestModeButtons,true);
await UpdateButtons(NormalModeButtons,false);
return;
}
await UpdateButtons(TestModeButtons,true);
await UpdateButtons(NormalModeButtons,false);
}
private async Task UpdateButtons(List<Button> btns, enable)
{
foreach (var btn in btns)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
new DispatchedHandler(() => { btn.IsEnabled = enable; }));
}
}
As it's written above, this behaves like btnReset_Click()... where the UI updates are "one step behind". However, if I add ".ConfigureAwait(false)" to each await in the event handler, then it becomes synchronous. I've done some reading on this topic, but don't fully understand it yet, and I would love for someone with a better understanding to help me understand it as it relates to my project.
You should not be doing any of that Dispatcher.Run and similar...
First stop and think and understand what your problem is and why the UI does not update.
Create a new thread where you control your motors (separate from the UI thread).
On the button clicks, call method on your motors thread.
When there are events on the motors thread where you need to update the UI, call (synchronously?) methods on the UI thread.
In a nutshell, consider these tips as you build your app:
Never call .Wait() or Result or otherwise try to block on an asynchronous operation on a UI dispatcher thread
If you do want to create worker threads to do blocking operations, try await Task.Run(...) for its simplicity (you can create raw threads but it's more work). Same for busy-waits like while(notDone) ; // empty
From a background thread (such as one created by Task.Run), if you want to update the UI then you would use Dispatcher.RunAsync(...) but only to set the properties of your UI
To disable your UI while a background thread does work, set IsEnabled=false or add a top-most emi-transparent interaction shield etc.
Also, try starting with something simple (eg, no hardware access; just use Task.Delay(...).Wait() to simulate blocking on the hardware). Once you have the UI basically working you can plug in the hardware calls.

WPF Progress bar working but blocked in UI thread even using async

I am trying to implement an indeterminate progress bar into my program. I'm new to threading, but as far as I know one of the best options here is to add an async method, and await the "heavy" function to perform its results. So I wrote this:
public void Window_Loaded(object sender, RoutedEventArgs e)
{
firstLoad();
}
private async void firstLoad()
{
LW.Title = "Loading...";
LW.Show();
filterTextBox.Text = defaultSearch;
await Task.Run(() => InitializeFilter());
}
private void InitializeFilter()
{
//Asynchronous???
Dispatcher.BeginInvoke(new Action(() => {
//... some lines of code that takes some time to run.
dataGrid.ItemContainerGenerator.StatusChanged += new EventHandler(closeLoadingWindow);
}));
private void closeLoadingWindow(object sender, EventArgs e)
{
if (LW != null)
{
LW.closable = true;
LW.Close();
}
}
firstLoad runs when the window is loaded, showing an indeterminate LW loadingWindow, and running the InitializeFilter() method (the heavy one). Finally, when the grid is populated and loaded, an event fires, allowing the LW window to be closed and closing it (if I didn't make it unclosable, a funny user could just close it clicking or using F4, which is not nice).
The system is working properly and everything works as expected regarding time frames, but the loading bar is frozen, not showing progress. The same LW bar works in the MainWindow with a similar set up What am I missing? Thanks in advance!
as far as I know one of the best options here is to add an async method, and await the "heavy" function to perform its results
The best option is to use Task.Run to move the heavy processing to the thread pool, and use await to retrieve its results.
The code as it currently stands uses Task.Run to move to the thread pool and then immediately turns around and uses Dispatcher to move back to the UI thread before doing the heavy processing. Thus, it's blocking the UI thread.
what this particular DataGrid displays is a CollectionView, which is not thread-safe.
Right, you can't update data-bound objects from a thread pool thread.
The best solution is to separate the heavy processing from the UI updates, something like this:
public async void Window_Loaded(object sender, RoutedEventArgs e)
{
await firstLoadAsync();
}
private List<FilterType> InitializeFilter()
{
//... some lines of code that takes some time to run.
}
private async Task firstLoadAsync()
{
LW.Title = "Loading...";
LW.Show();
filterTextBox.Text = defaultSearch;
var filterData = await Task.Run(() => InitializeFilter()); // Get the plain data on a background thread
myCollectionView = new CollectionView(filterData); // Update the UI
if (LW != null)
{
LW.closable = true;
LW.Close();
}
}
do not use your dispatcher. Microsoft had the foresight to use it's magic (SynchronizationContext) to be able to update the UI thread in a method that is being executed in an async context. This is demonstrated in their async/await example found here
while under previous/other circumstances, you would have to either marshal back to the main (UI) thread to update the UI thread, or wait until completed and retrieve the results from objects who share state. Since you are using async/await then you should be fine to not use the dispatcher, and update the UI directly.

Starting task in the button click handler causes aggregate exception

please help someone.
I want to create and start a new task in the button click handler and it always causes aggregate exception. I'm doing the following:
private void btn_Click(object sender, EventArgs e)
{
Task<Image> t = Task<Image>.Factory.StartNew(InvertImage,
TaskCreationOptions.LongRunning);
t.ContinueWith( task => {
some code here;
pictureBox1.Image = t.Result;
},
TaskContinuationOptions.OnlyOnRanToCompletition);
t.ContinueWith( task => { some code here },
TaskContinuationOptions.OnlyOnFaulted);
}
private Image InvertImage()
{ some code here }
The code if run in the main thread works perfectly, so here is definetely something wrong with my understanding of using Tasks. Thank you in advance.
By default continuation runs on default scheduler which is Threadpool Scheduler. Threadpool threads are always background threads so they can't update the UI components (as UI components always run on foreground thread). So your code won't work.
Fix: Get the scheduler from UI thread.This will ensure that the continuation runs on the same thread which created the UI component
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
and than pass it to ContinueWith function.
t.ContinueWith( task => {
some code here;
pictureBox1.Image = t.Result;
},
TaskContinuationOptions.OnlyOnRanToCompletition,scheduler);
In Winforms(or even in WPF) only the thread who create the component can update it you should make your code thread-safe.
For this reason the debugger raises an InvalidOperationException with the message, "Control control name accessed from a thread other than the thread it was created on." which is encapsulated as AggregateException because tasks encapsulate all exceptions in aggregate exception
you can use this code to iterate through all exceptions in aggregate exception raised by the task
try
{
t.Wait();
}
catch (AggregateException ae)
{
// Assume we know what's going on with this particular exception.
// Rethrow anything else. AggregateException.Handle provides
// another way to express this. See later example.
foreach (var e in ae.InnerExceptions)
{
if (e is MyCustomException)
{
Console.WriteLine(e.Message);
}
else
{
throw;
}
}
}
To make your thread safe just do something like this
// If the calling thread is different from the thread that
// created the pictureBox control, this method creates a
// SetImageCallback and calls itself asynchronously using the
// Invoke method.
// This delegate enables asynchronous calls for setting
// the text property on a TextBox control.
delegate void SetPictureBoxCallback(Image image);
// If the calling thread is the same as the thread that created
// the PictureBox control, the Image property is set directly.
private void SetPictureBox(Image image)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.picturebox1.InvokeRequired)
{
SetPictureBoxCallback d = new SetPictureBoxCallback(SetPictureBox);
this.Invoke(d, new object[] { image });
}
else
{
picturebox1.Image= image;
}
}
Another option to use a Task result within the calling thread is using async/await key word. This way compiler do the work of capture the right TaskScheduler for you. Look code below. You need to add try/catch statements for Exceptions handling.
This way, code is still asynchronous but looks like a synchronous one, remember that a code should be readable.
var _image = await Task<Image>.Factory.StartNew(InvertImage, TaskCreationOptions.LongRunning);
pictureBox1.Image = _image;

BeginInvoke on ObservableCollection not immediate

In my code I subscribe to an event that happens on a different thread. Every time this event happens, I receive an string that is posted to the observable collection:
Dispatcher currentDispatcher = Dispatcher.CurrentDispatcher;
var SerialLog = new ObservableCollection<string>();
private void hitStation_RawCommandSent(object sender, StringEventArgs e)
{
string command = e.Value.Replace("\r\n", "");
Action dispatchAction = () => SerialLog.Add(command);
currentDispatcher.BeginInvoke(dispatchAction, DispatcherPriority.Render);
}
The code below is in my view model (could be in the code behind, it doesn't matter in this case). When I call "hitstation.PrepareHit", the event above gets called a couple times, then I wait and call "hitStation.HitBall", and the event above gets called a couple more times.
private void HitBall()
{
try
{
try
{
Mouse.OverrideCursor = Cursors.Wait;
//prepare hit
hitStation.PrepareHit(hitSpeed);
Thread.Wait(1000);
PlayWarning();
//hit
hitStation.HitBall(hitSpeed);
}
catch (TimeoutException ex)
{
MessageBox.Show("Timeout hitting ball: " + ex.Message);
}
}
finally
{
Mouse.OverrideCursor = null;
}
}
The problem I'm having is that the ListBox that is bound to my SerialLog gets updated only when the HitBall method finishes. I was expecting seeing a bunch of updates from the PrepareHit, a pause and then a bunch more updates from the HitBall.
I've tried a couple of DispatcherPriority arguments, but they don't seem to have any effect.
I think you are blocking yourself.
The UI Thread is waiting at Thread.Wait, BeginInvoke sends the action to the dipatcher, however the UI Thread is busy waiting. That is why UI updates only get done after HitBall finishes, that is, when the UI Thread finishes processing.
To get around this, you should start the HitBall method's code in another thread, freeing the UI:
private void HitBall()
{
try {
Mouse.OverrideCursor = Cursors.Wait;
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
Action hitOperations = () =>
{
hitStation.PrepareHit(hitSpeed);
Thread.Wait(1000);
//Only needed if PlayWarning needs access to UI Thread
dispatcher.Invoke(() => PlayWarning());
hitStation.HitBall(hitSpeed);
dispatcher.Invoke(() => Mouse.OverrideCursor = null);
};
//Free the UI from work, start operations in a background thread
hitOperations.BeginInvoke(null, null);
}
catch (TimeoutException ex)
{
MessageBox.Show("Timeout hitting ball: " + ex.Message);
}
}
Also if the intended use of Thread.Wait(1000) was to wait for events to refresh the UI, with this implementation it is no longer needed.
Could it be something as simple as needing to raise the PropertyChanged event on your ViewModel?
You will probably not see updates from PrepareHit unless there is a context switch and there is no guarantee when context switch will occur (unless you block your current thread and that would increase the probability that a context switch will occur).
As iCe mentioned if you're doing this on the UI thread, then you might be blocking your UI. Does your UI block/freeze when you call Thread.Wait? If it doesn't then proceed reading below:
Update:
I can't think of anything that would not compromise concurrency... without compromising concurrency you could try to increase the priority of BeginInvoke: http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherpriority.aspx
currentDispatcher.BeginInvoke(dispatchAction, DispatcherPriority.Send);
By the way, it looks like Render priority is lower than Normal priority:
Render The enumeration value is 7.
Operations processed at the same
priority as rendering.
DataBind The
enumeration value is 8. Operations are
processed at the same priority as data
binding.
Normal The enumeration value
is 9. Operations are processed at
normal priority. This is the typical
application priority.
Send The
enumeration value is 10. Operations
are processed before other
asynchronous operations. This is the
highest priority.

Categories

Resources