How to set text to a TextBlock from a backgroundworker - c#

I want to show in realtime (updating every 1s for example) some temperatures to my program's interface.
To do this I believe I'm going to need to run some code in a background worker so the main program doesn't get blocked. My question here is if it's possible to set the text of a TextBlock from a background worker and if yes, how to do it.
This is the basic idea:
backgroundworker
{
while(true)
{
//reading and updating temperatures
//.....
}
}

BackgroundWorker has built in support for reporting the current progress of the work, which sounds like it's exactly what you're doing:
var worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += (s, args) =>
{
while (true)
{
Thread.Sleep(1000);//placehodler for real work
worker.ReportProgress(0, "Still working");
}
};
worker.ProgressChanged += (s, args) =>
{
textBox1.Text = args.UserState as string;
};
worker.RunWorkerAsync();
By leveraging the built in support you allow the background worker to handle marshaling to the UI thread. (It will ensure that all of the events besides DoWork run in the UI thread.)
This also has the advantage of separating the UI logic from the business logic, rather than embedding code for manipulating the UI all throughout code doing business work.

Related

How to ask the GUI thread to create objects?

I've got the following program flow in my Windows Forms application (WPF is not a viable option unfortunately):
The GUI Thread creates a splash screen and a pretty empty main window, both inheriting Form.
The splash screen is shown and given to Application.Run().
The splash screen will send an event which triggers an async Event Handler which performs initialization, using the IProgress interface to report progress back to the GUI. (This works flawlessly.)
At some point during the initialization, I need to dynamically create GUI components based on information provided by certain plugins and add them to the Main Window.
At this point I'm stuck: I know I need to ask the GUI thread to create those components for me, but there is no Control I could call InvokeRequired on. Doing MainWindow.InvokeRequired works neither.
The only idea I could come up with was to fire an event which is connected to a factory in the GUI Thread, and then wait for that factory to fire another event which provides the created controls. However I am pretty sure there is a more robust solution. Does anyone know how to achieve this?
Using the comments on my question, especially the note about the continuation method which made me find this very useful question, I achieved the following:
The first part of initialization is performed asynchronously (no change).
The second part of the initialization (which creates the UI elements) is performed afterwards as a Continuation Task, in the context of the UI thread.
Apart from the rather short GUI initialization part, the Splash Screen is responsive (i.e. the mouse cursor does not change to "Waiting" once it hovers the Splash Screen).
Neither of the initialization routines knows the splash screen at all (i.e. I could easily exchange it).
The core controller only knows the SplashScreen interface and does not even know it is a Control.
There currently is no exception handling. This is my next task but doesn't affect this question.
TL;DR: The code looks somewhat like this:
public void Start(ISplashScreen splashScreen, ...)
{
InitializationResult initializationResult = null;
var progress = new Progress<int>((steps) => splashScreen.IncrementProgress(steps));
splashScreen.Started += async (sender, args) => await Task.Factory.StartNew(
// Perform non-GUI initialization - The GUI thread will be responsive in the meantime.
() => Initialize(..., progress, out initializationResult)
).ContinueWith(
// Perform GUI initialization afterwards in the UI context
(task) =>
{
InitializeGUI(initializationResult, progress);
splashScreen.CloseSplash();
},
TaskScheduler.FromCurrentSynchronizationContext()
);
splashScreen.Finished += (sender, args) => RunApplication(initializationResult);
splashScreen.SetProgressRange(0, initializationSteps);
splashScreen.ShowSplash();
Application.Run();
}
It is much easier to manage multiple forms and display one while the other is working or being constructed.
I suggest you try the following:
When application is started you create splash screen form so your Program.cs is like this
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new SplashForm());
}
Inside the splash form constructor, create a new thread (I will use BackgroundWorker but there are other options like tasks) to build your main form.
public SplashForm()
{
InitializeComponent();
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerAsync();
}
Now we need to write the SplashForm member functions to tell background worker what to do
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
// Perform non-GUI initialization - The GUI thread will be responsive in the meantime
// My time consuming operation is just this loop.
//make sure you use worker.ReportProgress() here
for (int i = 1; (i <= 10); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
System.Threading.Thread.Sleep(500);
worker.ReportProgress((i * 10));
}
}
SetVisible(false);
MainForm mainForm = new MainForm();
mainForm.ShowDialog();
//instead of
//this.Visible = false;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
You might have noticed by now, I am using another member function to hide the splash screen. It is because you are now in another thread and you can't just use this.visible = false;. Here is a link on the matter.
delegate void SetTextCallback(bool visible);
private void SetVisible(bool visible)
{
// 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.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetVisible);
this.Invoke(d, new object[] { visible });
}
else
{
this.Visible = visible;
}
}
When I run this sample project it shows the progress bar and then loads the MainForm windows form after hiding the SplashForm.
This way you can put any controls that you might need inside the MainForm constructor. The part you shortened as // Perform GUI initialization afterwards in the UI context should go into MainForm constructor.
Hope this helps.

Update data information on the screen/display

I want my application updates the screen information while the code is executing. I tried with this.LayoutRoot.UpdateLayout(); but it didn't work and I don't understand why. Can anyone help me?
The application receive a button propriety from a button clicked, then use that to a several things in a Model class, and then I want it show a message to the user. after that i want it continue executing more things (AI)... :S
public void showMsgFromModel(string player, string msg)
{
if(player!="")
txNomeMsg.Text = player + ":";
else
txNomeMsg.Text = player;
txMsg.Text = msg;
this.LayoutRoot.UpdateLayout();
System.Threading.Thread.Sleep(1500);
}
You're trying to do some processing from the UI thread, which is therefore unable to update the interface.
Use a background worker to execute long-running tasks, and use the dispatcher when you need to update the UI:
var worker = new BackgroundWorker();
worker.DoWork += (s, e) =>
{
Thread.Sleep(1500); // Some processing
Dispatcher.BeginInvoke(() => txMsg.Text = "Hello"); // Update the UI
Thread.Sleep(1500); // More processing
};
worker.RunWorkerAsync();

How to program async processing of widgets?

I have list of files(widgets) that I need to do some work on. I want to do it in async manner so my interface stays responsive. I want to update UI with progress. Here is my prototype code. How do I accomplish this? I assume I need to utilize threading, but I also don't want to span all the threads at the same time, one by one is fine.
void Process()
{
var documents = GetDocuments();
foreach(document in documents)
{
ProcessDocument(
document,
status => this.TextBox.Text += status);
}
}
void ProcessDocument(Document document, Action<string> onCompleted)
{
}
You can use the BackgroundWorker class to process operation asynchronous in Windows Forms projects.
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += (sender, args) => {
var documents = GetDocuments();
foreach(var document in documents)
{
ProcessDocument(document);
worker.ReportProgress(0, status);
}
};
worker.ProgressChanged += (sender, args) => {
this.TextBox.Text += args.UserState.ToString();
};
worker.RunWorkerAsync();
You can use the System.Threading.Thread Class
Remember that you will need to used delegates to safe update the controls on your UI
you cant modify controls when running in other than the main UI thread.
If you want to do it easy without delegates because you think you can control it
you can set the property
Control.CheckForIllegalCrossThreadCalls=false
So you will be allowed to update controls without the Illegal Cross Thread check
If you prefer to use the BackgroundWorker class, this allow you to bind and Event called
ProgressChanged that allows you to update UI too
public void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//thread work
}
// This event handler updates the UI
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Update the UI here
}
Also consider Reactive Extensions, particularly IObservable<T>.
Framework 4.5 introduced the async/await keywords that simplify asynchronous .NET programming.
Have a look at TPL if you are using Framework 4.
If on the other you are using earlier versions of .NET (3.5 and older) then you should have a look at APM.

Update controls created in another thread?

I have two threads.
Thread 1: WPF thread. Shows a Window with all the information.
Thread 2: Loops constantly, receiving information & updates the Window in thread 1.
I have the following interfaces.
IModuleWindow
{
void AddModule(IModule module);
void RemoveModule(IModule module);
}
IModule
{
UserControl GetSmallScreen();
UserControl GetBigScreen();
}
IModuleWindow is implemented by the WPF window in Thread 1
IModule is implemented by an object, is instantiated in Thread 2, and then sent to thread 1.
I want to Add the UserControls in IModule to the Window object in thread 1, and show them. IModule objects get updated constantly in thread 2 and they have to change their text.
Basically the idea is that this program is supposed to show the state of objects in thread 2 , which gets updated constantly.
What is the best way to accomplish this in WPF?
IMO the best idea is to use BackgroundWorker, with the very handy ReportProgress method and ProgressChanged event.
The ProgressChanged event is raised on the GUI thread, so you can perform your updates to the GUI directly. Here's how you code should look like:
// initialize the worker
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerAsync();
// thread 2 (BackgroundWorker)
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// main loop
while(true)
{
// time-consuming work
// raise the event; use the state object to pass any information you need
ReportProgress(0, state);
}
}
// this code will run on the GUI thread
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// get your state back
object state = e.UserState;
// update GUI with state
}
It helped me lot to understand what i must do.
The scenario must be like that:
ObservableCollection images = new ObservableCollection();
TaskFactory tFactory = new TaskFactory();
tFactory.StartNew(() =>
{
for (int i = 0; i < 50; i++)
{
//GET IMAGE Path FROM SERVER
System.Windows.Application.Current.Dispatcher
.BeginInvoke((Action)delegate()
{
// UPDATE PROGRESS BAR IN UI
});
images.Add(("");
}
}).ContinueWith(t =>
{
if (t.IsFaulted)
{
// EXCEPTION IF THREAD IS FAULT
throw t.Exception;
}
System.Windows.Application.Current.Dispatcher
.BeginInvoke((Action)delegate()
{
//PROCESS IMAGES AND DISPLAY
});
});
You must use System.Windows.Application.Current.Dispatcher.BeginInvoke() for updating UI in WPF.
It would be nice to be able to use controls created at another thread,
thats what I want ideally
The short answer: forget it.
A UI control belongs to a single UI thread only. The best you can do here, is to create controls in main thread, prepare data in background thread, and update controls' properties in main (UI) thread again.
For data preparation I recommend use TPL.

Showing a progress bar that updates while creating a lot of controls

I've written a piece of code that creates a lot of controls and layouts them on a canvas to visualize a tree. Now this code can take a lot of time, especially since it sometimes has to query an external service to see if there are more child node.
So I would like to show a progress bar while this code is executing. For other parts of my program I use a background worker that reports progress. However since I have to create controls that are later interact-able I don't see how to use a background worker or other threading solution here.
Since this is WPF, I also can't call Application.DoEvents(). So my question is, how can I create a lot of controls while still being able to periodically update the visual part of the GUI?
For my other code I use an Adorner that I layout over the busy piece of my app, I would prefer a solution where I can keep using that, I would also still prefer a solution using BackgroundWorker, but I'm pretty sure that is not possible.
I've looked at other SO topics, but I can't find a good answer so far
Creating controls in a non-UI thread
Creating a WinForm on the main thread using a backgroundworker
Edit:
According to this MSDN article http://msdn.microsoft.com/en-us/magazine/cc163328.aspx the BackgroundWorker should automatically invoke asynchronously on the UI thread if required, but this is not the behaviour I'm seeing, since I still see a cross thread exception.
Edit2: nvm, that's not totally true: BackgroundWorker still needs to call Invoke?
Edit3: After some more reading and some tips, this is the solution I've come to. Anybody got any tips/hints?
// Events for reporting progress
public event WorkStarted OnWorkStarted;
public event WorkStatusChanged OnWorkStatusChanged;
public event WorkCompleted OnWorkCompleted;
private BackgroundWorker worker;
private delegate void GuiThreadWork(object state);
private PopulatableControlFactory factory = new PopulatableControlFactory();
public Canvas canvas;
public void PerformLayout(TreeNode node)
{
OnWorkStarted(this, "Testing");
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync(node);
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
OnWorkCompleted(this);
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var workTuple = (Tuple<GuiThreadWork, TreeNode>)e.UserState;
workTuple.First.Invoke(workTuple.Second); //Or begin invoke?
if (OnWorkStatusChanged != null)
OnWorkStatusChanged(this, e.ProgressPercentage);
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
TreeNode node = (TreeNode)e.Argument;
Thread.Sleep(1000);
worker.ReportProgress(33, Tuple.New(Place(node), node));
Thread.Sleep(1000);
worker.ReportProgress(66, Tuple.New(Place(node.children[0]), node.children[0]));
Thread.Sleep(1000);
worker.ReportProgress(100, Tuple.New(Place(node.children[1]), node.children[1]));
}
private GuiThreadWork Place(TreeNode node)
{
GuiThreadWork threadWork = delegate(object state)
{
PopulatableControl control = factory.GetControl((TreeNode)state);
Canvas.SetLeft(control, 100);
Canvas.SetTop(control, 100);
canvas.Children.Add(control);
};
return threadWork;
}
In short: I use the progressChanged event of the background worker because this is always marshalled to the GUI thread. I pass it a tuple of a delegate and some state. This way I always create the control on the GUI thread and do all actions there, while still being flexible.
Generally I don't use BackgroundWorker often but I can suggest the following:
Logic for DoWork - its executed on non UI thread
get count of nodes so you can report real progress
begin building tree ( and call Invoke on UI Dispatcher so UI thread
is adding nodes) and report progress to ReportProgress as (already
added nodes)/(total count nodes) while enumerating through all nodes
in ProgressChanged simply update some ProgressBar with new value

Categories

Resources