I am building a program that is supposed to watch some project folder for change in source code and then send these changes somewhere and in the process, log the files that were changed in a Windows Form TextBox.
The code looks something like this:
void Form_Load(object sender, EventArgs e)
{
FileSystemWatcher fsw = new FileSystemWatcher("C:\\test");
fsw.Created += File_Created;
}
void File_Created(object sender, FileSystemEventArgs e)
{
string name = Path.GetFileName(e.FullPath);
logs.Text += name + Environment.NewLine;
}
Of course, this is not the actual code but it's enough to see the point.
Every time the File_Created event is triggered, it creates a new thread and thus I'm unable to interact with the UI from that event, it throws an exception.
Everything else in my program works except the logging part but it's kinda annoying.
Is there a way around it?
Thanks,
Arik
If you want to update your UI from other thread you need to use:
Dispatcher.Invoke(new Action(() =>
{
logs.Text += name + Environment.NewLine;
}));
I hope this can help you
Related
In my main window, I have a button that generates a report. But the report takes about 15 seconds to build, so I simply want to put up a small dialog that asks the user to "Please wait". It then just goes away when the report window is activated. The below works except that the "Please wait" dialog only produces the shell of the window, no content.
Here is the code:
WD_PleaseWaitDialog _pWait = null;
private void ReportButton_Click( object sender, RoutedEventArgs e )
{
_pWait = new WD_PleaseWaitDialog();
_pWait.Show();
ReportWindow reportWindow = new ReportWindow(); // takes 15 seconds to execute
reportWindow.Activated += closePleaseWaitWindow;
reportWindow.Show();
}
private void closePleaseWaitWindow( object sender, System.EventArgs e )
{
_pWait.Close();
}
Thank you all for your answers. This is a great site and has provided me with lots of good info. This is what works, but it does not seem as elegant as I would like it to be:
private void ReportButton_Click( object sender, RoutedEventArgs e )
{
reportWindow = new BackUp.ReportWindow();
StatusBarTextBox.Text = "Generating report for \"" + DestinationDirectoryTextBox.Text + "\"";
StartWork();
} // END ReportButton_Click
private void StartWork()
{
_pWait = new WD_PleaseWaitDialog();
_pWait.Show();
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += WorkerCompleted;
worker.RunWorkerAsync();
}
private void DoWork( object sender, DoWorkEventArgs e )
{
reportWindow.initializeReportWindow( _dailyList, _weeklyList, _monthlyList, _semiAnnualList );
}
private void WorkerCompleted( object sender, RunWorkerCompletedEventArgs e )
{
_pWait.Close();
reportWindow.Show();
}
With this approach, I had to move the ReportWindow initialization out of the constructor and move it to an accessor.
Use dispatcher.begininvoke to generate and show report
Dispatcher.BeginInvoke(new Action(()=>{ /* report window */ });
What's happening is that your WD_PleaseWaitDialog gets instantiated and when you Show() it, it goes into Loaded state, but that's right before Rendered lifetime state. This is when you are creating your ReportWindow, which takes a while to process (15 seconds according to you). What's happening is that you're essentially blocking the main thread during that time, which prevents WD_PleaseWaitDialog from completing its rendering phase of its lifetime cycle. By the time your ReportWindow finishes its loading, both of them get rendered, but it's so quick that you may not see the content of the WD_PleaseWaitDialog at all before it's closed.
There are a couple of things you can do...
You might try working with the ContentRendered event of the WD_PleaseWaitDialog in order to proceed with the rest of the code. But, that couples the two windows... and that's not something I personally prefer.
You may consider using different threads. Task class can greatly help you in this. One way this may be done is to put lengthy operations in your ReportWindow into a Task:
Task.Run(() => { // lengthy operation here });
When you're done with the operation, you'll need to call back into the main thread to close your WD_PleaseWaitDialog (since you can't handle UI operations in other threads):
Application.Current.Dispatcher.BeginInvoke(
Dispatcher.Normal, new Action(_pWait.Close));
I'm not going to provide you the whole code unless you get really stuck. Try to do it yourself, since I've given you plenty of information to get started. Hope that helps.
I hate that my first question seems to have been answered many times, but I'm still having a tough time getting my head around how to call a method using BackgroundWorker.
I'm processing a very large text file using a series of classes and methods. The entire process is kicked off after the user selects a tool strip item. Sequentially, it goes like this:
User selects the tool strip item
User selects a file to be processed via a dialog box
The action starts
I think I can wrap everything into BackgroundWorker from the moment the user pops the initial dialog box, but what I'd like to do for now is just put the method where all the heavy lifting is done into its own instance of BackGroundWorker. I'll add a ProgressBar, too, but I think I can handle that if I can just get the BackgroundWorker process rolling.
From the top (pseudocode used for example purposes. Much omitted for brevity):
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
string fileName = openSingleFile.FileName;
processFile(fileName);
}
static public void processFile(string fileName)
{
// many vars/loops exist but not shown
foreach (data in bigData)
{
processItem(stringA, stringB); // <-- this method is where the expensive work is done
x++;
}
}
I've created an instance of BackgroundWorker...:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Things go here
}
...and I've tried too many things to list, so I've gone back to the beginning for the presentation above.
If I'm understanding BackgroundWorker, I'll need to do the following:
Replace processItem(stringA, stringB) in the above code with something like:
backgroundWorker1.RunWorkerAsync(processItem(stringA, stringB));
...and then do some type of DoWork call?
...and then do some type of RunWorkerCompleted call?
Not sure why my brain is freezing, but I'm embarrassed at the amount of time I've spent on this with no result. Any help would be greatly appreciated. Without StackOverflow, I would have been DOA a long time ago.
FYI: I've referenced other SO posts, MSDN, and DotNetPerls examples. I'm just missing something conceptually, I suppose.
Replace processItem(stringA, stringB) in the above code with something like...
No, that's how you got in trouble. You most definitely want to move the processFile() call to the worker. There is no perceivable benefit from running processItem() in a worker, at least not in the snippet you posted. And doing so is difficult, it would require starting more than one worker. One for each item. Having a lot of workers that each do little work is not very healthy. If it is really necessary then you don't want to use BackgroundWorker, you'll want an entirely different approach with several Threads that consume packets of work from a thread-safe queue. Don't go there if you can avoid it.
The only non-trivial problem to solve is passing the string that processFile() needs. Luckily BackgroundWorker.RunWorkerAsync() has an overload that takes a single object. Pass your string. Obtain its value in your DoWork event handler, casting e.Argument back to a string. Thus:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
string path = (string)e.Argument;
processFile(path);
}
private void processToolStripMenuItem_Click(object sender, EventArgs e) {
backgroundWorker1.RunWorkerAsync(openSingleFile.FileName);
processToolStripMenuItem.Enabled = false;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
processToolStripMenuItem.Enabled = true;
}
Starting up a new background worker is an expensive operation. You don't want to be starting one for each iteration of a loop. Instead, put the entire loop inside of a single background worker's scope.
When ToolStripMenuItem_Click is run create your background worker, have processFile be what is done in the DoWork event handler.
Make sure that when doing that work you're really just doing that work, not updating the UI. You'll want to separate business logic from the user interface. If you want to update the UI with some current progress then call ReportProgress and ensure that there is an event handler to properly update the UI.
If you need to update the UI when the work is all done then you can do so in the RunWorkerCompleted event handler. If the work you are doing generates some result that is used to update the UI use the Result property of the background worker to pass it from the DoWork method to the completed handler.
BackgroundWorker bgw;
In the Load event or constructor:
bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
//bgw.WorkerSupportsCancellation = true;
bgw.DoWork += bgw_DoWork;
bgw.ProgressChanged += bgw_ProgressChanged;
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
/
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
string fileName = openSingleFile.FileName;
bgw.RunWorkerAsync(fileName);
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
string fileName = (string)e.Argument;
processFile(fileName);
}
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int Progress = e.ProgressPercentage;
//Update progressbar here
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Job completed
}
How can I fix this issue ?
I am expecting the progressbar to load during process untill process it is done
Here is my code:
private void btnProcess_Click(object sender, EventArgs e)
{
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//start transaction
DoTransaction();
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
My transaction function:
private void DoTransaction()
{
string pathIdentifier;
pathIdentifier = func.checkthePathFile();
if (pathIdentifier == null)
{
MessageBox.Show("Path has no yet been specified!");
}
else
{
//create xml base from user inputs
XElement transactXML = new XElement("Transaction",
new XElement("CardNumber", txtCardNum.Text.Trim()),
new XElement("ExpireDate", txtExpDate.Text.Trim()),
new XElement("Cardtype", txtCardType.Text.Trim())
);
//save xml to a file
transactXML.Save(pathIdentifier + "/sample.xml");
}
}
How is the runtime supposed to know how far along your process is?
You need to tell it by calling backgroundWorker.ReportProgress from the background operation. No magic here.
MSDN: http://msdn.microsoft.com/en-us/library/ka89zff4.aspx
Break down your process into meaningful chunks and ReportProgress whenever it makes sense to do so.
public void DoTransaction()
{
part1();
backgroundWorker.ReportProgress(25);
part2();
backgroundWorker.ReportProgress(50);
part3();
backgroundWorker.ReportProgress(75);
part4();
backgroundWorker.ReportProgress(100);
}
Edit Based on Posting of Transaction() function
If you are not confident in writing multithreaded programs, then do not attempt to write multithreaded programs, even with the help of a BackgroundWorker which tries to abstract some of those details away from you.
A few issues:
Your provided Transaction() method attempts to launch a MessageBox and read the Text property of various controls from the background thread. This is going to cause problems as the runtime typically throws an Exception when UI elements are accessed from a thread other than the one which created them.
If you really want to do the XML saving in the BackgroundWorker, you should validate the filename and directory, and save the Text properties to an intermediate object before setting up the BackgroundWorker and calling RunWorkerAsync.
Furthermore, in my opinion, your Transaction method is not going to be time intensive enough to truly warrant a background thread. Even a relatively old PC will be able to create and save a 15 element XML file faster than you can blink. The runtime will probably waste more time marshalling data between the threads than it would to simply write the file out to disk. Just do your work in the button click event handler.
needs some reference to the BackgroundWorker instance.pass the reference to the class when instantiating it.
instantiate like this
BackgroundWorker worker = sender as BackgroundWorker;
then call like this
`worker.ReportProgress(...)`
I'm a fairly new to .net and I'm still struggling to understand a lot things, and right now I'm trying to accomplish something relatively simple but I've failed every single time, I would like to add a Thread to my program, this Thread would be responsible to perform the Upload operations to a web server and keep my program responsive providing the feedback of the operations to my users by updating a ListView, where the users would see all the status of the file uploads.
I don't know how to put this Thread inside the program to make it responsive, I couldn't find any examples so far and I'm trying to find a little sample to show me the use of Thread and WinForms in action.
What you'll want to use is a BackgroundWorker. It's specifically designed for exactly this purpose.
private void button1_Click(object sender, EventArgs e)
{
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += (_, args) => LongRunningTask(bgw);
bgw.WorkerReportsProgress = true;
bgw.ProgressChanged += (_, args) =>
{
textbox1.Text = args.ProgressPercentage.ToString();
};
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
bgw.RunWorkerAsync();
}
private void LongRunningTask(BackgroundWorker bgw)
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);//placeholder for real work
bgw.ReportProgress(i);
}
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do stuff when completed.
}
A key point to note is that the DoWork event runs in a background thread, but the other events all run in the UI thread. The BackgroundWorkder class takes care of ensuring that all on its own.
I am having fun with WPF and got a problem. I have googled and found this website that has the same problem of me but without any working solution.
The problem is that I have a button that do some processing of data (around 30 sec). I want to have the button to disable and to have log writing in a text box... the problem is that it doesn't disable and it doesn't wrote any thing on the textbox until the processing is completely done.
Any idea?
private void button1_Click(object sender, RoutedEventArgs e)
{
this.button1.IsEnabled = false;
//Long stuff here
txtLog.AppendText(Environment.NewLine + "Blabla");
//End long stuff here
this.button1.IsEnabled = true;
}
As others have said, use the BackgroundWorker or some other method of doing work asychronously.
You can declare it under your Window, initialize it somewhere like the Loaded event, and use it in the Click event. Here's your method, modified to use BackgroundWorker, assuming you've declared it under the Window as _bw:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_bw = new BackgroundWorker();
_bw.DoWork += new DoWorkEventHandler((o, args) =>
{
//Long stuff here
this.Dispatcher.Invoke((Action)(() => txtLog.AppendText(Environment.NewLine + "Blabla")));
});
_bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler((o, args) =>
{
//End long stuff here
this.Dispatcher.Invoke((Action)(() => this.button1.IsEnabled = true));
});
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this.button1.IsEnabled = false;
_bw.RunWorkerAsync();
}
Note that anything that modifies your UI from another thread must be done within a Dispatcher.Invoke or Dispatcher.BeginInvoke call, WPF does not allow you to get or set DependencyProperty values from any thread but the one where the object was created (more about this here).
If you wanted to read from txtLog instead of modifying it, the code would be the same:
//Long stuff here
this.Dispatcher.Invoke((Action)(() =>
{
string myLogText = txtLog.Text;
myLogText = myLogText + Environment.NewLine + "Blabla";
txtLog.Text = myLogText;
}));
That operation is being performed on the UI thread. This means that it will block the Windows message pump from processing until it has completed. no pump = no UI updates. You should launch the job on another thread. I don't know WPF, but in C# I would use either the Thread or BackgroundWorker classes.
do it async. create a backgroundworker process to handle the data and the application will continue to respond. MSDN Resources on the Class. Since WPF is using C# (or VB.net) you can still use the same types of threading objects. I've used the background worker successfully in a WPF app myself.