On a button press I call a background worker to change the colour of some text, and in the DoWork method it creates a new object and executes one of its methods. Here is the code:
private void StartProcessButton_Click(object sender, EventArgs e)
{
FirstTimeBackgroundWorker.RunWorkerAsync(GenKeyLabel.ForeColor = Color.DodgerBlue);
}
And the DoWork method...
private void FirstTimeBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
KeyFile k = new KeyFile();
k.CreateDummyFile(DLetter);
}
[The CreateDummyFile effectively does a bunch of file processing, such as copying,deleting and creating files (up to 4.0MB). Throughout I call the ReportProgress method and change some GUI elements on the form, however as it does it in one chunk I cant see the constant progress or the GUI elements change]
Now it does what its supposed to inside the CreateDummyFile method, however it executes it as if it wasn't in another thread (like when you press a button to do something and the form would freeze, and then just show the final result). Any ideas why this is? What I am doing wrong?
There is a lot of code in that class that gets executed so I can't just place it inside the DoWork method.
EDIT: Removed all of the ReportProgress's and it still only changes one of my GUI elements. (All I do is change the font.forecolour. Apart from this I am changing the text on a status strip...
You need to add the FirstTimeBackgroundWorker_DoWork as a handler of DoWork event on BackgroundWorker:
FirstTimeBackgroundWorker.DoWork += FirstTimeBackgroundWorker_DoWork;
Also make sure if you're calling back the UI to update it to do so on the UI thread, not from the background one.
Related
private void buttonSave_Click(object sender, EventArgs e)
{
textBox1.Text = "DATA is being copied.";
//my own function to cpy files, working properly
copyDirectory(sourceFolderPath, destFolderPath);
}
Copying takes 3 seconds, but i cannot see TextBox with text="DATA is being copied. before it goes into the copyDirectory function", it only updates the text box after finishing copy, what is the Problem? i am not using another thread in copying.
This is because of how Windows Forms handles events. Windows Forms is executing all events synchronously. Which means that when a button is clicked, all code in all attached events are executed, before anything else happens.
This means that until the copying finishes (that is, the method returns), the textbox will not be visibly updated.
There are several fixes for this. One fix is to have the button click start a timer, that executes 100 milliseconds later. And then when the timer executes, perform the copying.
Another (my preferred) would be to execute the copyDirectory method inside a Task:
Task.Factory.StartNew(() => copyDirectory(sourceFolderPath, destFolderPath))
Note: This means that the code runs on a different thread, so if you want to update the textbox to say something like "Completed!" when it's finished, you'll need to do this
Invoke(new Action(() => textbox.Text = "Completed!");
In windows form on click on Next I need to display other form and start some processing. Am coding in .Net C#
The problem is before the form is complete visible, the method gets triggered and the processing starts and the UI looks like it crashed. Processing started even before controls are loaded. and once processing is done all controls are visible.
The actual output must be all controls should be loaded and then processing must start.
I need to call the method to start processing after the form (user control) is visible and is loaded completely.
I tried this and this, but no luck.
Added code:
private void FeatureRemovalControl_Load(object sender, EventArgs e)
{
pictureBox2.Image = Properties.Resources.line;
prgbar.Value = 0;
//code to load images and some other stuff
StratProcess();
}
You're calling StartProcess (which seems to block until it's finished) from your UI thread. Because WinForms repaints occur on that thread, nothing is painted, and it appears that your process has hung. You should look at using a BackgroundWorker, or other way to call StartProcess asynchronously.
Best way, if you ask me, would be to start processing asynchronously, so that you maintain full control of the UI and process at the same time.
http://msdn.microsoft.com/en-us/library/2e08f6yc(v=vs.71).aspx
Try calling that method at the end of the FormLoad event, the control should have finished loading by then. If it hasn't that you may need perform some checks and possibly create a custom event that fires when you're happy that it is ready.
Another solution is to have a button that the user must press to trigger the processing, which they will only be able to click once everything has loaded
EDIT: The reason it look's like it's happening is because you're starting the process in one of the control's load method, which I assume is not the last control to load, so it's starts processing before the other controls are given a chance to load. Make StratProcess method public and call it in the FormLoad method of the parent form instead, like so:
private void ParentForm_Load(object sender, EventArgs e)
{
FeatureRemovalControl.StratProcess(); // Should it be called StartProcess instead?
}
Beware though this is still doing the processing on the UI thread, so the screen may appear to 'hang' whilst this is happening so I advise you move it to a background thread as others have suggested.
I am stuck and was hoping someone could help me.
I have made a class/gui with a loading bar set to marquee so that when a task is being carried out i could display it to the user.
In one of my gui classes, in the constructor on the first line i am making a new instance of this class and then doing
LoadingBar bar = new LoadingBar();
Thread thread = new Thread(bar.Show);
thread.Start();
However, even tho the main programme thread is going off doing some more intensive stuff, this gui still seems to freeze, even if i use backround worker.
Is there anything wrong with the approach i have mentioned and if so what do i need to change?
Thanks
You need to reverse your method. The GUI needs to stay in the main thread while the work is done in a "worker thread" (typically a BackGroundWorker). Then the worker reports back to the GUI which then updates.
You'd better do the opposite. Make your intensive work in the thread (or a background worker), and show the wait screen in the main application thread.
You need to use a BackgroundWorker. Drag one onto your form, click backgroundWorker1 and set the WorkerReportsProgress property to True
Then goto the events (via the properties window) and attach handlers for
DoWork, this is where all the work that is represented by the progress bar. You will "report progress" via this and the background worker will make sure ProgressChanged is called on the UI thread.
ProgressChanged, this is where you update the UI based on progress and state data reported to the method
DoWork event looks something like this
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var userState = new StateClass();
while (working)
{
// TODO: do work here
// update the state surrounding this task via userState
userState.property = "some status";
// report the progress so that backgroundWorker1_ProgressChanged gets called
this.backgroundWorker1.ReportProgress(percentComplete, userState);
}
}
ProgressChanged event looks like this
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// e.UserState contains the state data you passed to ReportProgress,
// you have to cast it to the right type though, since its of type object
var userState = (StateClass)e.UserState;
int progress = e.ProgressPercentage;
// TODO: report progress to the UI with the above variables
}
Now all you have to do is tell the background worker to do work by calling
this.backgroundWorker1.RunWorkerAsync()
I don't think you're doing all your work within the background worker or the GUI wouldn't be freezing. We'll need to see more of your code or you'll need to have another look at background worker examples to see what could be wrong.
EDIT
Add a call to System.Threading.Thread.Sleep(1); after your report progress call
Hi
I'm opening a form like this from my main form when the user makes a selection of a menu item.
private void commToolStripMenuItem_Click(object sender, EventArgs e)
{
Command_Form Command_Form1 = new Command_Form();
Command_Form1.ShowDialog();
// Command_Form1.Dispose(); this didn't help
}
Inside the form "Command_Form1"
I close it like this when the user clicks on the close button
private void Close_button_Click(object sender, EventArgs e)
{
this.Close(); //I get the exception here
}
This process works fine once but on the second closing of the form
(Which I hope is a completely different/new instance of the form) I get the error in the title of this post.
This is the output in the debug window.
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
All the topics that list this error go on about not trying to do anything to a form that has not been displayed but this happens when I click on a button in the form.
It would seem to me that pretty much ensures the form has been displayed if I'm able to click its button.
The other posts I've found that list this type of error go on about making thread safe calls so I tried this as an experiment but it didn't make any difference.
private void Close_button_Click(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
CloseCallback d = new CloseCallback(Close_button_Click);
Invoke(d, new object[] { sender, e });
}
else
{
this.Close();
I have multiple threads in my application but they are created by the controls I'm using not by me explicitly.
I am passing data from a serial port to/from the form by Marshling the received/sent data via a delegate[s].
It makes sense that the serial port would run on a different thread than the form but why would a button click on a form be in a diffrent thread than the form????
The whole thread thing is very confuzing
How do I figure out what threads originated where and what is going on in the threads that I didn't create explicitly?
Why would I need to invoke the form's close method via a delegate?
Heck is there anything I can do in this multi threading environment that is thread safe How in do I know if what I'm doing is unsafe/safe if I don't know what/where/why/who/when is creating threads?
My guess is your close() call is not throwing that exception, but something that happens after close(). Have you stepped into the code with the debugger to see when it is fired?
As to when you need to invoke...There is only one thread allowed to make changes and access dynamic properties on the GUI, call it the GUI thread. The GUI thread is responsible for updating layout, firing events like buttons, etc. If you ever access the GUI from another thread (like a timer event) you need to use invoke() to queue your function to be run on the GUI thread. BeginInvoke will also queue the function but is asynchronous (will only queue the function to be run on GUI thread, but will not wait for it to finish).
Close_button_click will only be called by your gui thread when the button click event fires(unless you explicitly call it somewhere else in your code behind, not recommended!), so invokeRequired=false in your code above, and the invoke code is never executed.
I have some WinForms in my application.
On some form , I am loading other forms which have lot of data to show.
So when I click a button to load these forms they take, 9-10 seconds to load,
I wana improve this. I have heard about Background thread but don't know how to use this.
Means on the button click what should i do so that I can see my form imidiately and the processing is done by background thread ?
Please guide me so that I can improve my UI.
Getting the form to show immediately, should be fairly simple and you don't need a background thread to do it.
My guess is that you are retrieving all that data prior to loading the form or you are retrieving the data on the same thread that loads the form. You should be able to call the form with the data it needs to retrieve the rest of the data (such as ID's).
Then you just need to find a way for the data processing to happen on a thread other than the thread that creates the form.
This may not be the most elegant solution, but it gets the job done. It uses a System.Windows.Forms.Timer
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
//fill controls with data
}
If you have several sets of data that you are retrieving, you may want to consider setting up a queue of tasks to retrieve each set.
Any way that you do it. Make sure to disable any buttons(or other ui) that could cause errors if the data is not loaded.
Edit: It should be noted that winform controls don't always play nice with threads. The nice thing about the System.Windows.Forms.Timer (as opposed to System.Timers.Timer)is that it designed to play nice with controls.
BackgroundWorker are easy to use. Mainly you subscribe to DoWork event, this is where you'd put your work that will be done in a seperate thread. And you also subscribe to RunWorkerCompleted event. This will get raised when your DoWork has completed.
In this method you'd simply bind the data fetched by the DoWork method.
You can use the DoWork eventarg to pass data between DoWork and RunWorkerCompleted.
You can also cancel the work and also the you can use the RunWorkerCompleted eventArg to get the data from the DoWork and also inspect the Error property for exception handling.
IF you have lots of data, you can use a batching process, to get data per batch and display them into your UI. You can show how many total records will be fetch and the progress of it 100 out of 1000 have been loaded, 200 out of 1000 have been loaded etc, to keep the user informed. You could also provide a Cancel option so the user can stop the fetch.
In your button click you'd simply call myBackgroundWorker.RunWorkerAsync().
this will call your DoWork Handler which will be done in a seperate thread not the main UI Thread, so your UI will not FREEZE during the background worker DoWork.
The backgroundworker also support report progress.
If your problem is the main form Freezing, what you need is to collect the data on a separated Thread than the Main form is running.
To achieve that, you can do something like this:
BackgroundWorker worker;
public Form1()
{
InitializeComponent();
worker = new BackgroundWorker();
}
private void button1_Click(object sender, EventArgs e)
{
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
//Collect data and open your second form here;
}