Specific working example needed using IProgress interface described by Albahari - wpf

I am a neophyte at C# threading. I am trying to get my head around how to make 100K web requests, with some degree of parallelism, and report progress real-time to the GUI:
urls processed so far: ######
total moved so far: ######
timed out so far: ####3
I am reading pages 596ff in C# 5.0 in a Nutshell by the Albahari brothers, the section on Progress Reporting. At this point, I don't see how in the Progress instance these counters would be incremented in a thread-safe manner, and exactly how/where the UI gets updated. EVen in the example specifically discussing the differences between writing to the console and writing to the GUI, the book uses Console.WriteLine. I'd be grateful for an example showing exactly what occurs in the Progress instance -- incrementing some int variables and writing to a textbox, for example.

I have a walkthrough on my blog, in particular pointing out the caveats:
IProgress<T>.Report is asynchronous, so it works best if the object you send it is immutable.
By convention, the IProgress<T> progress passed into your TAP method may be null, so check for that before reporting progress.
Progress<T> works best with a UI or other single-threaded SynchronizationContext.
Exceptions raised from Progress<T>'s handler go directly to the SynchronizationContext, so avoid throwing exceptions from the progress report handler.
There's also a blog post here and the MSDN docs are quite good.

Related

What causes VisualTreeHelper::HitTest to return incomplete results, and sometimes no results?

I had a scenario where I was connecting to a Windows WPF app, through a network connection to drive UI for the purposes of test automation.
Sometimes my requests to the UI using VisualTreeHelper returned no results regardless of the apparent state of the logical or visual trees.
This, more than a question is the documentation of the solution to the problem.
It turns out that I was detecting the network connection availability and IMMEDIATELY after it responded, I issued calls that exercised VisualTreeHelper and catching the UI while being rendered. The result of that call was incomplete and subsequent calls failed completely (no elements were found ever).
My practical solution was to delay for 2 seconds between when the communication was open, and the first call to VisualTreeHelper. That eliminated the weird state caused by calling UI too soon. I tested with 100 iterations of the app rebooting with no problems.
I 'Googled' the problem but didn't find good results.
Interestingly, I asked ChatGPT about it and it informed me:
"If you try to access elements of the visual tree before they have been fully rendered, you may get unexpected results, or an exception may be thrown."
I asked the bot to tell me what sources it had for the assertion and the only link I got:
"here's a link to the Microsoft documentation that mentions the risk of calling VisualTreeHelper before the visual tree is fully rendered:
https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.visualtreehelper.getchild?view=netcore-3.1#remarks"
Unfortunately such link actually doesn't mention anything like that. This may be due to ChatGPT using 2021 data, and the link content has changed.
A friend suggested I used archive.log (an Internet archive) to see if a previous version of such link had the desired information, but none was found.
ChatGPT provided relevant information, but could not provide sources where it distilled it from.
Lastly, I acknoledge that the 'ideal' way to address the problem of racing to use VisualTreeHelper before the UI is done rendering is to wait for an event the main window calls:
private void MainWindow_Loaded(object sender, RoutedEventArgs e);
and gate any use of VisualTreeHelper until this event is raised.
My approach is not stricktly the ideal, but practical with little effort. The 2 second delay does not significantly impact my scenario.
After I delayed 2 seconds before using VisualTreeHelper to wait for UI to render, I had no problems.
The short answer is (as you have observed) that they're not there yet when you try finding the controls.
The visual tree that the visual tree helper works with is the object graph of UI controls etc which are within a window.
A window is a content control.
When you instantiate a window, the window itself is created using the constructor.
I'm not sure there's a point where there can be just the window itself in the visual tree but this is conceptually how it works.
Parent windows is first then the root panel content and the content of that root.
The "tree" of controls is window > content panel > child controls.
Constructing a window can take a while. 2 seconds seems kind of slow but developers are prone to putting all sorts of things in constructors. The time taken may vary depending on how much code the developer has put in there, connectivity speeds etc etc.
That variance would explain why a test result will vary.
The correct event to handle for a window would be contentrendered. As the name suggests, this fires after all the content of the window has been rendered.
With a usercontrol or page you can handle loaded but you're best deferring processing via use of dispatcher. Loaded doesn't guarantee everything is rendered.

DotTrace no clear big amount of user code execution time

For my work I used DotTrace to analyze slowness one of our cliënts experiences in our WPF desktop application.
I used it before to do this which resulted in the conclusion that the DataBase calls where slow which we could then find a solution for.
This time however, I see 75% of the execution time in Native code and no clear slowness in the user code.
I searched some around and saw a few other people with the same question.
The answer there was either that it's normal (previous snapshot also had just a tiny part of execution time in user code, so that seems okay) or that you can analyze it further if you check the box "Collect native allocations" when making the snapshot (which I unfortunately didn't check).
If I check just the user code most of the execution time resides in DevExpress DLLs which are third party UI components. Could you then say that this is moving towards hardware related slowness (see User code part of the snapshot below)?
I used the Timeline option to create the snapshot.
My questions:
Since the snapshot doesn't show a lot of time in true user code (excluding the DevExpress components), could I then conclude that this slowness isn't caused by inefficiency in our code?
Can I tell anything from the native code part of the snapshot (see screenshot below)?
Is Timeline even handy for this case or are one of the other sampling options clearer?
How would I proceed in such a case to move close to the source of the slowness?
Thanks in advance for your help!
Sebastiaan
Native code part of the snapshot:
The native part is always called by the managed code.
The timeline is not efficient in this case. Here you filtered only the native part.
For this kind of analyzing, i recommand using the Sampling mode where you have a better view of your hot spots. The native part will still be there but you can see which managed code called it.

Detecting Printer State Change with Cups Api

Using the Cups c api I am able to see the state of a printer (such as paused, printing, jammed ect.) What I am trying to do now is to listen for, or lock against a change in a printer's state. Ultimately I want a live view of a printers state, but I don't want to have a delay loop spamming cups with printer attribute requests.
I have seen many functions and tags in the source code and documentation that hint towards some kind of event system, but I have been unable to figure out how to utilize it. Any help is welcome, even just pointing me towards the right function.
I used this example in my current implementation to get state information. http://cups-dev.easysw.narkive.com/9RO0OBnZ/how-to-get-printer-status-via-cups-api
It ends up this was a very complex question and involved a lot of work to figure out. The only sane way I found to listen for changes was to use the rss notification system. I would advise against attempting to make your own notification module, I wasted a week of my life trying that (I'm not even sure it is possible anymore). Use the Create-Printer-Subscription with a uri like rss://localhost:8000. You will of course need a listener waiting for the xml data.
I put up an a simple debugging tool I made with java/jna here. Select 2 to set up a subscription, you will need to listen for the data yourself though.

ExtJs component cleanup

I read the following comment in ExtJs-in-action -
'Do not dismiss the destruction portion of a Component’s lifecycle if you plan on developing your own custom
Components. Many developers have gotten into trouble when they’ve ignored this crucial step and have code that
has left artifacts such as data Stores that continuously poll web servers...'
I have never called explicit destructors/destroy on my my containers/components in 3.4.x
Though things seem to work fine - I am curious on
1. What are some instances where implementing destructors becomes essential
2.what is the proper convention to handle component destruction on close of browser instance.
This guide may be a good read.
You should always consider cleaning up your objects after they are needed to free up memory, especially unbinding event listeners and any timers you've created with setInterval. Once the object reference is destroyed you cannot access it but it could still be listening to or firing events and using up resources.
Generally in ExtJs, You free up resources in the destroy method, but just remember to call the callParent() function too so that ExtJs does it's own cleanup.
Here is another article from IBM in 2012 that seems to go into more depth on the subject.

Am I a discoverer of a bug in the WPF engine?

We have a MFC 8 application compiled with /CLR that contains a larger amount of Windows Forms UserControls which again contain WPF user controls using ElementHost. Due to the architecture of our software we can not use HwndHost directly. We observed an extremely strange behavior here that we can not make any sense of:
When the CPU load is very high during startup of the application and there are a lot live of ElementHost instances, the whole property engine completely stops working. For example animations that usually just work fine now never update the values of the bound properties, they just stay at some random value after startup. When I set a property that is not bound to anything the value is correctly stored in the dependency property (calling the getter returns the new value) but the visual representation never reflects that. I set the background to red but the background color does not change.
We tested this on a lot of different machines all running Windows XP SP2 and it is pretty reproducible.
The funny thing here is, that there is in fact one situation where the bound properties actually pickup a new value from the animation and the visual gets updated based on the property values. It is when I resize the ElementHost or when I hide and reshow the parent native control. As soon as I do this, properties that are bound to an animation pickup a new value and the visuals rerender based on the new property values - but just once - if I want to see another update I have to resize the ElementHost.
Do you have any explanation of what could be happening here or how I could approach this problem to find it out? What can I do to debug this? Is there a way I can get more information about what WPF actually does or where WPF might have crashed? To me it currently seems like a bug in WPF itself since it only happens at high CPU load at startup.
I don't do any work with those techs, so I can't really speak to that. However, to me it sounds like some kind of deadlock is occurring in your code which is blocking calls to redraw() (or its equivalent). Resizing the window will force a redraw, but your normal mechanism for telling it to redraw when you've changed something might be blocked.
Is it possible you have a race condition in your code somewhere? On a lightly-loaded system things might happen in the correct order, but on the heavily loaded one the timing might be different. Perhaps that's triggering a deadlock in your code?
If you can attach a debugger, take a look at the threads that are running. If you can see what each thread is waiting on and what else it holds locks on (You can do this with Java, not sure about your app) that might help you determine where it's dying.
There is no detail on how you load your data on startup... If you haven't done it yet, consider using Dispatcher.BeginInvoke (with a priority lower than render) or a BackgroundWorker
Here is a post on how to do this!
PS. Just be careful if your objects that you bind to is an ObservableCollection<>... Read more about the issues I had doing this here
Most of the time, select isn't broken (as the saying goes).
It does sound very much like some kind of race or deadlock as #Herms suggests.
You could of course check MSDN for known bugs. Depending on what your code is like, when I'm really stuck with a bug I find that removing chunks of code until you're left with a minimal test case usually helps.
Nothing strange happens in your application. Dependency system "stops working" because of the fact, that UI thread, all the system relies to is busy. It's all about priorities for different Disparcher objects. I can consider you to use background processes doe for prolong operations, while all synchronization done in UI thread.
Also, you can play with task prioritization (DispatcherPriority enum as first parameter of Invoke/BeginInvoke methods)
Another tip, can help you is to implement DoEvent pattern, known from WinForms (to process messages in windows queue)
To summarize, you should remember, that you're working in STA. Also, when you're using ElementHost in Windows XP, you actually remove hardware acceleration. Try to use .NET 3.5 SP1 to fix it somehow, but still you have to leave CPU for rendering and dispatching things.

Resources