I have a simple C# 4.0 Windows Forms form that make an instance of a FileSystemWatcher which watches a directory. When a file is added, the proper event fires, and I do some stuff in another directory. Then I make an instance of a child form. The child form hangs, and controls do not paint.
I think this is because the FileSystemWatcher is on a different thread, even though it looks like I am launching from the main form. What is the proper way to call a child form from a FileSystemWatcher event on what I think is another thread?
Set the FileSystemWatcher.SynchronizingObject property to your main form.
MSDN:
When SynchronizingObject is null, methods handling the Changed,
Created, Deleted, and Renamed events are called on a thread from the
system thread pool. For more information on system thread pools, see
ThreadPool.
When the Changed, Created, Deleted, and Renamed events are handled by
a visual Windows Forms component, such as a Button, accessing the
component through the system thread pool might not work, or may result
in an exception. Avoid this by setting SynchronizingObject to a
Windows Forms component, which causes the methods that handle the
Changed, Created, Deleted, and Renamed events to be called on the same
thread on which the component was created.
Related
I had a suspect that a bug in one of my Codename One projects was caused by concurrent executions of the same listener (if the user taps a button very quickly more times, invoking its listener before it ended the execution)... I added a lock variable in the code, to avoid multiple executions at the same time, and this solved the bug.
This is my first time that I have this kind of problem. Reading on the web, it's suggested to use the synchronized Java keyword (however I'm not sure if it can be useful in this case).
My question is if the synchronized Java keyword is supported by Codename One.
synchronized works fine in Codename One but if you used an action listener it's unlikely that it solved the issue unless we have a huge unimaginable bug.
All events, paints, lifecycle methods etc. are invoked on the EDT. It's a single thread so two clicks on the button will happen on a single thread. synchronized would be meaningless. The EDT is used from the touch screen interaction all the way down to the event on the component itself and you can test that through the isEDT() method.
A more likely scenario is that one of the action listeners on the button uses invokeAndBlock which can trigger weird side effects in the event dispatch chain. invokeAndBlock() is used internally by AndWait methods, dialogs etc.
Using syncronized will prevent concurrent execution of the method, but will essentially queue up the request that are made, by forcing threads to wait for any current execution.
When handling this scenario, you might want to debounce the button clicks, by preventing user interaction for some period after it is first pressed, or for the duration of the resulting computation, by disabling the button and re-enabling it
I am putting together a Silverlight 5 application that will run out-of-browser and has a bit of everything on start-up. Specifically, here are the steps I need to follow:
Check that the app is running out of browser (if not, display a screen instructing the user to install it locally).
Display a "splash screen" (it would be nice if this would play animations while the remaining steps execute).
Configure MEF
Pre-load context information and 'static' data from the server (for example, settings). This data is required before any of the application logic can run.
Dynamically load additional XAP files including an external theme library.
Replace the "splash screen" with the shell which contains a navigation frame.
Navigate to the application's start page.
I also need to support Application Extension Services (IApplicationService, IApplicationLifetimeAware) so any process I implement must respect these services. Most of these services will require MEF to be configured, so they should not execute before MEF has been configured and imports satisfied.
Another consideration is that some imports may be satisfied only after the dynamic XAP files have been pulled in and MEF recomposed.
One of the hurdles I'm running into is the fact that I cannot do step 5 until the previous steps are complete. Loading the XAP files or calling the server for data asynchronously allows the code to proceed. I need a way to "stall" the UI until all of the composition is complete and all required context data has been loaded.
So, I'm looking for recommended approaches that satisfy all of these requirements and am happy to provide more details if that helps get to a working solution.
UPDATE
The best explanation I can give for my difficulty is that I must 'release' the UI thread to display a 'splash screen' but also suspend the normal life cycle of the application while each step executes. I can't (and don't want to) do everything in the Application.Start event handler because application services will have already started.
Plus, releasing the UI thread means I do work in the background and let the original method (Application.Start, for instance) return and the runtime will move forward in the startup process. For example, starting a background process in the Starting method of an application service then returning allows the runtime to raise the Start event on the Application object. But if I need the background process to complete before I can do the next thing, I have to suspend the current thread which blocks the UI.
So I'm not sure how to divide up the work or where to put it (App, application service, bootstrapper, workflow, etc.).
You can use ManualResetEvent class to force the service calls to be Sync (and guarantee the order they complete). You could also use this to synchronize the background thread to the main UI thread.
http://mohundro.com/blog/2006/06/27/a-little-bit-about-manualresetevent/
I am having a bit of a problem with a WPF application. The application loads from a database and then creates a bunch of own made Usercontrols. When I load lets say 1000 of these Usercontrols the UI thread blocks. Now I have tried multiple things with loading the Usercontrols on a different thread and then adding them to the main thread, but that is simply not possible I found out (or somebody must have a proper working example).
Is it possible to create a thread with a loading animation that is not blocking while the main UI thread is doing things?
Perform most of work in the thread that loads data from database and use Dispatcher class
http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx
to perform the UI related operations on the main thread.
I'm building a single window WPF application
In the window is a list items (which are persisted in a database of course)
Periodically I need to start a background task that updates the database from an Atom feed. As each new item is added to the database, the list in the UI must also update to reflect this. I don't want this background task to slow down the UI but at the same time it needs to interact with the UI.
Having read loads of articles and seen lots of simple examples, I am still unsure of the best way to implement this.
What I think maybe I could do is:
On the Window_Loaded event, create a DispatchTimer.
When the Tick event fires, call UpdateDb() method.
UpdateDB() will get the items from the Atom feed and add to the database. As I iterate through each item I will call another method to rebind the list to the database so that it "refreshes".
When all the tasks are finished reset the DispatchTimer ??? (not sure if this can / needs to be / done).
Remember, this is background task so a user could be using the UI at the same time.
How does this sound?
Thanks.
This sounds suboptimal because you're doing database connectivity on the UI thread. When the Tick event fires on the DispatcherTimer, handlers will execute on the UI thread. You need to minimize the amount of work you do on this thread to keep the UI responsive, and you definitely shouldn't be doing IO-bound work on this thread.
I would probably have a data service whose responsibility is to update the database and raise events as changes are made. Your UI layer can attach to these events and marshal to the UI thread to apply changes. To marshal to the UI thread, you just need to call Dispatcher.Invoke.
Regardless of your specific approach, the key is to do as much as you can (including any database access) on a separate thread. Marshal back to the UI thread as late as possible and do as little work as possible on the UI thread.
One other thing to note is that WPF automatically marshals changes to scalar values for you. You only need to marshal changes to collections (adding/removing/replacing items).
Your approach would work.
You'd start the timer when the app loads. For each tick of the timer, you start a thread to update the database. Once the database update has happened, you can call .BeginInvoke() on your UI objects to update the UI on the presentation thread (that will be the only time your UI should be affected).
I'd use a System.Threading.Timer, which will call a specified method at a specified interval on a threadpool thread, so no need to create an additional thread, do your db work with that and marshal back to the ui thread as needed.
WPF Multithreading with BackgroundWorker by Pavan Podila:
The good news is that you really don’t have to write such a component since one is available already: the BackgroundWorker class introduced in .Net Framework 2.0. Programmers who are familiar with WinForms 2.0 may have already used this component. But BackgroundWorker works equally well with WPF because it is completely agnostic to the threading model.
A VB6 application is using the Interop Forms Toolkit to work with forms written in .NET. The documentation for the toolkit advises calling a method on the toolkit to advise the toolkit when the VB6 application is shutting down.
The VB6 application uses a Sub Main procedure that loads a splash screen, then displays several modeless forms. When Sub Main completes, the application is still running. How can the application detect that it is shutting down and call the cleanup method on the Toolkit?
In a module (probably the same one that contains Sub Main), create a public sub (e.g AppCleanUp) that will hold your cleanup code.
Add a class to your project (e.g. clsAppCleanup). In this class, add code in the Class_Terminate event handler that calls the sub you created in the previous step.
In a module (probably the same one that contains Sub Main), define a variable of clsAppCleanup.
In Sub Main, instantiate the clsAppCleanup.
When the app is shutting down, The terminate event on the class will cause the cleanup code to run.
Its been a while since I wrote in VB6 but if I remember correctly you can use the Unload event to call your cleanup code (it similar to the closing event in .net). You can also check that there are no other forms in the VB6 app still running
Create a module that contains a FormCount variable. This variable will be shared by all forms in your application. Increment the FormCount variable in every form's Form_Initialize method. Decrement FormCount in every form's Form_Terminate method. When FormCount drops back to 0, you can notify your form toolkit that of the forms have been unloaded.
You won't have to worry about multi-threading issues because VB6 creates single-threaded applications, so one form's Initialize (or Terminate) method will run to completion before any others begin execution.