c# delegates – 2 fundamental categories

Update: java 8 lambda. [[mastering lambds]] P 5 mentions AA BB DD as use cases for Command pattern

AA — is the main topic of the book
BB — https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
DD — http://www.oracle.com/technetwork/articles/java/lambda-1984522.html and http://www.drdobbs.com/jvm/jdk-getting-a-head-start-with-lambdas/240008174

Today I finally feel ready to summarize the 2 usage categories of c# delegates. If you are new like me, it’s better to treat them as 2 unrelated constructs. Between them, the underlying technical similarities are relevant only during initial deep dive, and become less important as you see them in various patterns (or “designs”).

In java, these features are probably achieved using interface + other constructs. Dotnet supports interfaces too, but in some contexts offers more “specialized” constructs in the form of delegates. As shown below, in such a context interfaces are usable but less than delegates.

Most tutorials would start with unicast delegate, without the inv list.

Coming from a java or c++ background, you will want to find a counterpart or close equivalent to delegates. Almost hopeless for BB. For AA there are quite a few, which adds to the confusion.

AA) lambda as function AAArgument
* I believe compiler converts such a lambda into a STATIC method (there’s really no host object) then bind it to a delegate Instance
* often returns something
* Usually _stateless_, usually without captured variables.
* predominantly unicast
* Action, Func and Predicate are often used in this context, but you can also use these 3 constructs as closures, which is a 3rd category beyond AA and BB
* Domain? Linq; functor argument as per Rajesh of OC
* Before java 8, often implemented as an interface or an anonymous inner class

BB) event field Backed by a multicast delegate instance (See other posts on “newsletter”)
* Usually NON-STATIC methods, esp. in GUI context
* Usually returns void
* A callback method is usually _stateful_, because the callback method often does its job with “self-owned” i.e. this.someField objects, beyond the argument objects passed in
* event is a pseudo _f i e l d_ in a class. Static field or non-static field are both common.
* Domain? GUI + asynchronous WCF
* we must register the callback method with the event source.
** can lead to memory leak
* in java, implemented by several callback Objects supporting a common interface (cf swing)

Some of the other categories —
CC) CCClosure — stateful, seldom passed in as a func arg
DD) thread start
EE) Passing in a delegate instance as a function input is the lambda usage (AA). How about returning from a function? P83 [[c#precisely]] shows examples to return an anon delegate instance. This is an advanced and non-trivial unicast use case. The underlying anon method is usually static and stateless

In a source code with AA, we see lots of custom delegate Types created on the fly.

In a source code with BB, delegate Instances take center stage, since each instance is assigned to a … pseudo field. The delegate type is less complicated.

memory leaks in one WPF/Silverlight app

The app has multiple screens (windows). A user can open and close them throughout a login session.

The acid test – when we close a data-heavy window, actual memory usage (not the virtual) should reduce. In our case, memory stayed high. In some cases it reached 1G+ and the entire application crashed. We fixed the issue – capped at 300M.

The leaks and the fixes

* Event registration was found to be the #1 category. In window OnClose, a lot of clean-up was needed. Release references, unregister events.

* Dispose() method was added to many classes.

some random comparisons – wpf ^ swing

I'm no expert. Just some observations of a newbie

* jtable vs grid

* dependency property, attached property – fundamental in wpf. No counterpart in swing.

* events (field-like delegate fields) are used throughout wpf, not only for event-handlers on a visual component (like button's mouse-click)

* the containment hierarchy is central to wpf command routing, event routing, property inheritance, and data binding. In swing, ……

* property change listener is another area to compare

* declarative programming via xaml? Many basic functionalities of xaml can be achieved in c# code, which looks like swing code.

* routed event? How does swing handle it?
* commanding? No such feature in swing.
* in both technologies, a visual object comprises many constituents.

AttachedProperty – clarifying questions

Attached Property is a tricky construct. When confused, a beginner (like me) could ask a few key questions

Q: Which class (not “object”) defines the AProp?
Q: Which object’s (not “class”) hashtable holds the property value?

The holder object is the visual/screen object “decorated” by the property value. Just like Opacity, “Dock.Left” describes some aspect of a visual. The “provider” is a class not an object. The AProp provider class is like a category or namespace, and tells us what category this property falls into. Is it a docking property or a text formatting property?

Any AProp (or any DProp) data can be seen as a key-value pair. In the Dock example, an OKButton’s hashtable holds the value of “Left” under the key DockPanel.DockProperty. Note the property is “specified” or “defined” not by Button class but by the DockPanel class.

After the OKButton saves the “Left” value, the natural question is who reads it? Answer — The container. In this case, the user of this property happens to be an instance of the provider class — DockPanel. In some cases, the user is unrelated to the AProp provider. You can even attach a nonsensical property to a nonsensical object, so the property value is never used.

dispatcher ^ dispatcherObject in WPF — some simple tips

Probably a low-level detail we seldom need to know. Don't spend too much time here.

See P928 [[Pro WPF in c#]]

I feel DispatcherObject means “UI object under a UI dispatcher”. Every visual (including Button) derives from the type System.Windows.Threading.DispatcherObject. See http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.asp

DispatchObject as a base class also offers the popular methods
– this.CheckAccess() and

– this.VerifyAccess()

Every DispatcherObject (including myButton) has a this.Dispatcher property, whose type is  System.Windows.Threading.Dispatcher

y minimize code behind xaml

I feel this is a valid question. Many wpf designs make this a high priority. It takes extra effort. Why make the “sacrifice”?

Code behind is a melting pot paradigm. In contrast, code in VM, M and command classes are far easier to read, test and modularize. They are often much shorter. These classes often have very few members. To a certain extent, I would say the more classes you use to organize the code, the better — imagine all of these logic put into one class — the code behind:(

See also http://stackoverflow.com/questions/3878610/why-keep-code-behind-clean-and-do-everything-in-xaml

Codebehind is considered part of Xaml and in the View layer. The code logic in CB is married to the view and not Reusable.

It’s considered best practice to
– move stuff from code behind to xaml or
– move stuff from code behind to VM or other c# classes

The reverse is usually easier — quick and dirty, sometimes clever manipulations to achieve an effect. These manipulations done in CB tend to be messy and not modularized or compartmentized.

tricks – wpf/swing IV

As my friend Guillaume pointed out, a lot of GUI know-how fall into the “tricks” category. Just open any cookbook on WPF/swing. (Let's not elaborate why GUI technologies have this commonality.)

Q: How would you deal with “how-would-you” interview questions ☺

A: prioritize according to rarity. Avoid those tricks less widely needed

A: prioritize among the visual components by rarity. jtable is by far the most used jcomponent in swing. I wasted a lot of time over text-related components.

A: real time application and related tricks are priority

A: memory management is priority but there are no feature “tricks” here

A: prioritize according to layer. Some knowledge is fundamental and used in a lot of tricks. Perhaps browse some books


*dependency property, attached property

*event handler

xaml resource dictionaries – a few pointers

What's the confusion with RD elements “” and WR

elements “”?

1) All these elements define an INSTANCE of the ResourceDictionary

class. If you see 5 chunks of it in a xaml, then in the VM there will

be 5 instances(?).

2) I believe most visual controls have a non-static property

Resources, of type ResourceDictionary. Therefore Each layer on the

containment hierarchy should offer a ResourceS field, often empty. You

can populate it like

See http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.resources.aspx

3) This “Resources” field often encloses a RD element, instantiating

an RD instance. Often the element simply define the

key/value pairs, without an RD layer — Confusing.

4) The resource dict instance at any Container level is available to

be shared by the children. The highest level is probably Application

level, but i usually use the Window level. That meets my basic needs

of sharing a resource.

[[wpf succinctly]] points out

You can create a resource dictionary at the Application, Window, and

UserControl levels. A custom RD allows you to import your own C#

objects to use (and share) in XAML data binding.

A common practice is to put your view model Instance in a window-level

RD. See [[wpf succinctly]]. This resource must be defined before it's

used as a data context.

ObjectDataProvider, learning notes

I feel ObjectDataProvider is an unsung hero….

One of the usages is binding to non-static method of some stateful util class. See also [[wpf recipes in c#]]. First you need to put an instance of your class into a resource dict. ObjectDataProvider element with an “ObjectType” attribute would instantiate it.
It's useful to put an instance of your stateful util class into the window's resource dict. You can later use it in many ways (won't elaborate). Without ObjectDataProvider, the instance is constructed by the default ctor — serious limitation.

wpf – suppress a keyboard/mouse event

… standard events like MouseDown, KeyUp.

P682 [[wpf recipes]] presented a surprisingly brief yet complete solution. The sample code takes fewer than 10 lines of xaml and c#,

but it's good to point out the salient features —

– no command, just routed events

– this technique requires a containment hierarchy, which exists in every WPF window

– If you want to suppress an event within a container, then apply the trick at that container level

– Trick is on the Preview tunneling event

wpf topics for IV, Proj

–IV + proj
data templates

dprop (dependency property), aprop (attached property)?
routed events
routed commands
logical ^ visual tree

items control
resource dict
user controls
containers – details
event handling – deeper
various common controls
bind to a method

command methods using VM — a few observations

In most of my projects, my commands inevitably need access to the VM. The Execute() and CanExecute() all need to access the VM. (See

other posts why VM is one of the top 3 players in a command set-up.)

Q: how does the command methods get a handle on the VMs? I know more than 1 technique.

A: [[wpf succinctly]] shows that in xaml, we can pass the VM as CommandParameter into the Execute() method

A: ctor injection — VM is constructor-injected in the command instance.

In a way, the command objects and VM objects are inter-dependent.

0) The VM often exposes the command as a CLR property, to be accessed by the xaml “Hollywood”

1) The command methods directly uses the VM object.

To reduce coupling, perhaps we can introduce interfaces. Necessary?

a little trick to avoid ViewModel referencing View #tight coupling

In my project a view model’s method VM.RepaintColors() needs to modify a View object DataGrid.

By basic OO principle, we know views “depend” on ViewModels, so ViewModels should not depend on (or directly edit the properties of) Views. When a data change needs to bubble up to view, we use the event infrastructure to notify the binding system to re-query the ViewModel objects.

Therefore my design above was a violation – VM.RepaintColors() directly manipulates DataGrid. I eventually solved the problem using event notification. RepaintColors() was moved into MainPage.xaml.cs i.e. the code behind class (I know this is anti-MVVM but still an improvement). As part of the view, CodeBehind (CB) class has full access to all ViewModel objects and View objects. Therefore if the original VM. RepaintColors() implementation need any field of the VM object, it still has access.

Remember the VM used to call this.RepaintColors() inside its various methods. Now with this change, it must fire the event RepaintColorsNeeded. This would notify the listening  CodeBehind and trigger CB. RepaintColors() method. The hook-up is by event registration —

Right after the CodeBehind instantiates the VM, it registers CB. RepaintColors() with the VM’s RepaintColorsNeeded event.

Note despite the notation in this write-up, RepaintColor() is always a non-static method, and uses the non-static fields.

collection view ^ collection view source, my take

My conclusion — many constructs in this space have limited practical value — CV base type, CVS.

http://www.zagstudio.com/blog/466 is an authoritative comparison.

* CVS (not CV) can be constructed in xaml.
* CV and CVS can both be used in c# cod, but i feel almost *always* we only use a subtype of CV.

CVS is designed to support __simple__ custom sorting/filtering etc directly in xaml. First You inject the collection into your CVS instance, then secondly you retrieve the view from CVS and inject the view into the visual (items control). A CVS instance is a wrapper over 2 objects
– The physical collection (often an ObservableCollection)
– A CV (or subtype) object

I guess a CV baseclass instance isn’t terribly useful if you want any customization — see below. Instead, you either use a CVS or a CV subclass instance
– For __simple__ sorting, use cvs in xaml
– For sophisticated sorting that demands c# coding, cast the CV to one of the 2 subclasses. This is the standard and natural choice.

http://www.zagstudio.com/blog/441 seems to agree with my guess.

As other authors pointed out, we should and could avoid using a view that’s a CollectionView base type — poor performance, no sorting/grouping. A subtype like ListCollectionView is always preferred. This is easy as most of the time, physical collection is some kind of IList. Therefore, whenever we retrieve the view as a CV, we almost always cast it to a subtype.

define a custom attached property

Once we reach a basic understanding of something sophisticated like Attached Property, looking at a custom AProp implementation could bring us to the next level.

http://msdn.microsoft.com/en-us/library/cc903943(v=vs.95).aspx points out

“If your class (the Provider class) is defining the attached property strictly for use on other types, then the provider class does not need to derive from DependencyObject. But you do need a DependencyObject as the method parameter in the getter/setter.

Define your attached property as a dependency property by declaring a public static readonly field of type DependencyProperty.”

Content vs Resource in a WPF build (MSVS)

If your wpf app needs to access a file (like my.jpg, or my.xml or whatever), you can include it with MSVS build-action CONTENT or RESOURCE.

1) RESOURCE (Avoid “EmbededResource” –  irrelevant) – will embed it in the assembly. No more separate file my.jpg in deployment.

2) CONTENT – will not include it in assembly but somehow registers (relative path to) the “loose file”. In the deployment, we usually put the loose file in the same folder as the assembly, so the application can reference this file with the bare name.

3) Sometimes you are lucky to get away without telling the builder about the file . Not recommended. As far as possible, any file needed by the app should be “included” somehow.

4) However, if the file name is known only at run time then it’s technically impossible to “include” it at build time. Must try other tricks.

DProp ^ CLR prop as SOURCE of data binding

See other posts on INPC. This is just another quick learning note.

You need INotifyPropertyChange if you use a regular property as Source of data binding. The host class (usually a VM) need to

implement INPC. Otherwise, changes to the property won't show up.

Is INPC required if the source is a DProp? I don't think so.

If you bind a regular collection (as Source) to an items control, then the collection class must implement INotifyCollecitonChanged,

otherwise add/delete won't show up. ObservableCollection is a subclass.

AttachedProperty # first lesson

AProp is one of the sophisticated features in WPF IMHO. First get a grip on DependencyProp (DProp) — see other blog posts.

–motivation for AProp–
If you want a concrete justification for AProp, look no further than Dock. Many top top WPF experts pick Dock as the showcase of AProp. Don’t read about StackPanel or FontSize. Don’t both with inheritance – we will deal with them much later.

Focus on #1 usage. Don’t bother with the #2 or #3, such as the “inheritance” or the “service” patterns in http://msdn.microsoft.com/en-us/library/ms749011.aspx#howused

Spend enough time and go deep enough to understand the Dock usage, before digging deeper.

Here’s the Dock usage outlined on MSDN. “The DockPanel.Dock property is created as an attached property because it is designed to be set on child controls within a DockPanel, rather than on DockPanel itself. The DockPanel class defines the static AProp named DockProperty, and then provides the GetDock and SetDock *static* accessors for the AProp.

–storage of the AProp values–
Same as ordinary DProp. One hash table per child DependencyObject. Absolutely Irrelevant is the hash table of the dock panel.

[[Pro WPF & Silverlight MVVM]] says “Once a DependencyProperty is registered as an attached property using the DependencyProperty.RegisterAttached method, that property can be set on any DependencyObject subclass.

–how to set/get–
In xaml, the aprop “Dock” looks comfortably like any other property of the child (eg Button), but we know that DockPanel not Button defines this property. Therefore the setter has to be defined in DockPanel. A Xaml declaration would translate to

   DockPanel.SetDock(myButton, Dock.Left); //STATIC method call

Internally, this runs

  buttonArgument.SetValue(DockPanel.DockProperty, Dock.Left); //AP setter

Look at this AP Setter 3 times, 5 times until you clearly understands —

* SetValue() is a NON-static method defined in the base class DependencyObject. Internally this method uses that hash table thing. All DProp and AProp setters goes through this Choke point.
* Note the dock property is unrelated to the host object i.e. the button. This is the funny/magical thing about Attached Property.
* Physically, the button object’s (NOT the panel’s) hash table records key={theButton.type + DockProperty.name}, value=Left. This property is useful to the parent container (the doc panel) during layout. The dock panel will scan all children, querying this button’s dock property, and another button’s doc property …

MSDN said “Attached properties are a XAML concept, whereas dependency properties are a WPF concept“. The way you set a AProp is very natural in xaml but not in code.

–extreme freedom–
The top top experts like to emphasize the extreme flexibility to attach anything to anything, whether meaningful or not.

Bencon said something like “simplest way to explain an attached property is that it allows the place where the property is defined and the place where it is stored to be completely different classes that know nothing about each other. Property value can only be stored on DependencyObject objects (which happens to be the base class for most Avalon things).”

Nick said things like

“You can call panel.SetValue(CheckBox.CheckedProperty, true), and property engine will happily set that attached property to true. Doesn’t matter that nobody is ever going to try to read that property value. Doesn’t matter that the author of CheckBox probably never intended this.”

“From a property engine perspective, it’s irrelevant that Button happens to be inside a DockPanel. You could set DockPanel.Dock even if your parent is a Grid — that property won’t do any good, because Grid doesn’t look at the DockPanel.Dock property, but you can do it.”

Bencon – http://blogs.msdn.com/b/bencon/archive/2006/07/26/more-advanced-attached-property-use-the-ramora-pattern.aspx
Nick — http://blogs.msdn.com/b/nickkramer/archive/2005/08/25/456024.aspx
MSDN — http://msdn.microsoft.com/en-us/library/ms749011.aspx#howused

gridbag-container = most versatile layout in swing/wpf

In swing/wpf, there exist 2 most versatile/flexible layout techniques — nested container  vs gridbag. It's also possible to combine the 2 techniques.

“Gridbag container” is a generic term.

* In wpf, the standard grid panel would meet this requirement.

* In Swing, we can use a JPanel with a gridbag layout manager.

* in html, we use a html table. Soon after I started using html, i realized (often nested) table is THE standard way to layout an html page.

However, popularity is different —

* in wpf, grid container is widely used and often the default container.
* in swing, gridbag container is too hard and seldom used.

## xaml’s job duties in a GUI app (in broad-strokes)

#1) lay out – the controls within a “container”. Lay out each sub-panel and sub-sub-pane. Lay out each leaf-node control in each panel.
** This is also html’s main job.
** strictly a Containment hierarchy, or “object tree”, good for xml
** containment hierarchy is needed for routed command and data context

# binding – command (+event handlers) to input controls
# binding – data binding to VM, with updates in both directions
# implicitly create instance fields (aka data members) of the code behind class
# style triggers

Which of these can be replaced with c# code? See other blog posts.

wpf tree-grid (like swing tree table)

I feel treegrid is the most useful variation of a grid

is a xaml-only clever solution, without third-party tools.

http://www.codeproject.com/Articles/30721/WPF-TreeListView-Control is a different xaml-only solution.

http://dotnetlearning.wordpress.com/2010/09/19/treelistview-in-wpf-containing-heterogeneous-hierarchical-data/ is another xaml-only

## most useful xaml keywords, briefly

[[WPF unleashed]] has a one-pager on xaml keywords. I trimmed the list further to just 3 —

– x:Name specifies a name for a xaml element, which would become an instance field in the code-behind class. This is mostly to make it accessible programmatically. Handy!

– x:FieldModifier defines the visibility of that field, which is internal by default. Can be public, private etc. You can specify a field modifier for each x:name

– x:Code – embeds c# code in a cdata block

– x:XData? Took me a while to find a usage example. http://learnwpf.com/post/2006/03/20/How-do-I-bind-to-XML-data-in-WPF.aspx embeds an “island” of static data in xdata, and uses it “locally” in subsequent xaml. It’s kind of nice to collocate data + visual next to each other.

xaml – declarative ^ programmatic

[[Dynamic .net 4.0 applications]] P155 claims that

“Xaml is completely optional. Anything you can accomplish in xaml, you can accomplish in source code”

If you do that your c# code will be like swing. Verbose, with large number of objects — every aspect of the visual is usually some property, represented by some object.

Biggest Power feature — you can write code to “set up” what is usually declared in xaml. Programmatic set-up is dynamic, flexible, based on user input, not hardcoded in xaml. Xaml is declarative, representing a major advancement over the traditional programmatic approach. Here we reverse the trend.

There are many more xaml techniques when we combine the programmatic + declarative. One example http://www.codeproject.com/Articles/19112/Dynamic-User-Interfaces-in-WPF

You can easily write code to access the object tree (a type of object graph), whether it’s in xaml or created by code. This access is so easy that I feel xaml format was designed for programmatic access.

wpf dock panel ^ swing border layout

I don't remember the details of swing border layout. Dock panel is similar and fairly flexible.

Based on http://www.codeproject.com/Articles/30904/WPF-Layouts-A-Visual-Quick-Start

Red 1

Green 1


Blue 2

Yellow 1

Orange 1

Green 2

Note it matters which region is declared first.

– Left is declared before Bottom, so Left region swallows all real estate. The later-declared Bottom region is “constrained”.

– If we move the Bottom declaration ahead of Left, then Bottom region swallows all real estate, and Left region would be constrained.

delegate command with(out) CommandManager

Now I feel you can implement a basic delegate command with or without CommandManager. (My sample wpf application description is in another blog post.)

A) The original RelayCommand by Josh Smith uses CommandManager. With CommandManager, we developers don’t need to add InvalidateRequerySuggested() after some VM state change, since CommandManager will take care of that.

One consequence is, the CommandManager fires a hell lot of activity via (static) event CommandManager.RequerySuggested. Since our custom CanExecuteMyCommand() callback is in the inv list, it gets called every time.

B) Some prefer a home-grown delegate command without CommandManager. Event firing is better understood and less opaque than with CommandManager. However, we do need to remember to add something like MyCommand.RecheckStatus() in many places.

Here’s my guess — Since the inv list is no longer provided by CommandManager, we must provide it in our delegate command class. There’s one inv list per command instance. By contrast, the CommandManager has one application-wide inv list for all the command instances. The inv list is behind the application-wide static event.

who subscribes to the ICommand.CanExecuteChanged event@@

I put a breakpoint on the event add{} and found out exactly which object is subscribing to the ICommand.CanExecuteChanged event.


————— wpf_proj_readme.txt —————–

This entire wpf app has a single VM. Among other things it defines a bool method vm.CanExecuteSave(). Note VM isn’t subclass of ICommand; TanBinRelayCommand is. It’s just a generic relay command class.


Xaml has a textbox and a Save button. Textbox is data-bound to a string property in VM; button to an ICommand property in VM – consistency. Entire xaml uses the VM as the only data context, so all data bindings are between the xaml (visuals) and the VM (properties) – consistency.


This vm.CanExecuteSave() method (wrapped in a delegate) is passed in when instantiating TanBinRelayCommand, the Command object behind the button. Therefore button “dimmer” is connected to vm.CanExecuteSave() method. Later at runtime the button is dimmed when CanExecuteSave becomes false.



Question is how does the runtime know when to requery CanExecuteSave(). The solution, as a standard pattern, is event subscription. Specifically, the button adds this.OnCanExecuteChanged() method into the inv list of the ICommand.CanExecuteChanged event.   But when is this method added into the inv list? At xaml initialization, HookCommand() performs this registration.


    abstract public class TanBinRelayCommand: ICommand{

        private Action methodToExecute;

        private Func<bool> isEnabled;


        public TanBinRelayCommand(Action methodToExecute, Func<bool> isEnabled)


            this.methodToExecute = methodToExecute;

            this.isEnabled = isEnabled;


        #region ICommand members


        /// who subscribes to this event? I think the command binding (or other objects in the xaml)


        bool ICommand.CanExecute(object obj) {

            if (this.isEnabled == null) return true;


            return this.isEnabled.Invoke();


        void ICommand.Execute(object obj)


            if (this.methodToExecute != null)



        abstract public event EventHandler CanExecuteChanged;


DelegateCommand – various sample implementations

http://wpftutorial.net/DelegateCommand.html is a simple and clean DelegateCommand class, very similar to my own. No complete WPF sample app included.

http://blog.rdeverett.com/post/812093504/wpf-delegatecommand is similar but a bit old-fashioned

http://relentlessdevelopment.wordpress.com/2010/03/30/simplified-mvvm-commanding-with-delegatecommand/ is similar

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx (MSDN) has a similar simple class named RelayCommand

wpf commanding – web of references

Too many cross-referencing in the commanding architecture. I'd say ignore the conceptual and focus on a typical implementation. Even

at the implementation levle, Commanding involves a web of references — non-trivial.

command source (typically a visual) often not always defines a command property and a command target property.

command target (typically a visual) often not always defineds a command binding and command handlers/reactors.

UI thread restriction in wpf/winforms, briefly

This is a popular question, and also an interesting question, for the curious. [[More effective c#]] says there are 2 reasons why we need Dispatcher or ControlInvoke —

1) STA — windows controls including those in .Net use COM Single-Threaded-Apartment model
2) message pump – the author said “many” (I would think all) of the controls use the message pump

http://stackoverflow.com/questions/2222365/what-is-a-message-pump has interesting comments on both 1) and 2)

wpf data binding – target Object holds the binding

One ticker (like the SPX last move direction — up or down) can drive 22 visuals controls. Each visual control is a target objects

and can have only one driver. In this case, there would be 22 binding Objects for the 22 linkages.

The binding object is injected into the target object, not into the source object. The single source drives 22 targets, so it can't

accept and hold 22 binding objects.

Remember both source and target must be properties. Therefore, one source Property drives 22 target properties. 2 of the 22 target

properties might belong to the same visual control (since one visual can have many properties like font, background…), but it's

not likely. Usually, the 22 target properties belong to 22 visual controls.

Incidentally, the source may not be a visual and may not exist on xaml. It could be a plain old property of a plain old object, but

this object needs to be visible to xaml, so xaml can bind to it. Alternatively, it can be visible to the code behind, so we can set

the binding in code behind.

ICommand instance CAN define actual action

When The MSDN article talks about ICommand, it only talks about one subtype i.e. the RoutedCommand. For RoutedCommand, the command instance doesn’t contain actual action, as echoed by other authors, but I am not sure if that is true across all ICommand implementations.

I think It’s possible to implement ICommand with a real Execute() method. See [[wpf succinctly]]

OneWayToSource, briefly

Logically, there are 2 sides to a (logical) binding — Source property and Target property. Both must be properties (not fields) of some class. Target must be a dependency property, not a plain property.

Behind the scene, there is a Binding object, with a Source field (not to be confused with the “source” property) and a Path field (Better rename to “PropertyNameInSourceObject”). You inject Binding object into the Target visual control. Once injected, the target visual is wired up to the source property, via the binding.

I feel target is usually a visual. Source property often isn’t a visual — it could be a plain property in a POCO object. When source property gets edited, WPF engine would somehow update the visual. That’s the plain vanilla OneWay update mode.

When used as a Target visual, some visuals default to 2-way update, like TextBox. Other visuals default to one-way update i.e. source to target.

OneWayToSource is a special mode. One reason you may need it — when exactly one of the 2 sides is a dependency property. By WPF policy that side must be the Target, whereas the non-dependency side will be Source. If you need to update the non-dependency side, you can use OneWayToSource. Imagine the non-dependency side could be a POCO object with a plain property, but you need to update it when the textbox gets edits. In summary, system automatically updates the non-dependency property from a visual control on screen.

When both source Obj and target Obj are visuals, we can often make do without data binding — use event instead.

one event delegating to another event – WPF

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030 shows an interesting mini “pattern” of one event (“event-pseudo-field”) delegating all its add/remove logic to another event (pseudo-field).

public event EventHandler CanExecuteChanged{
  add { CommandManager.RequerySuggested += value; }
  remove { CommandManager.RequerySuggested -= value; }

This reveals the true meaning of an event member. If an object studentA (of class Student) has an event pseudo field evt2, this field is basically a chain of callbacks (or notification targets, or event handlers). The evt2 field is nothing but a handle to add/remove on this chain.

In many cases, the callbacks run sequentially on the same thread as the event-firing code.

See also http://bigblog.tanbin.com/2010/06/field-like-event-syntax-restrictions.html

NPE and other exceptions in SL OOB

I’m no expert on SL OOB. I realize unlike in other environments, when an exception is thrown in a SL OOB, the consequence is unexpected. Blank screen is common.

Most common exception is NPE. If I get to see a log msg that’s good, but it doesn’t say in which thread on which line.

In other contexts I often throw exception to indicate error. At least the stack trace is logged. I now avoid throwing any exception. Rather I create an exception object and log it without throwing. Then I either close the application or continue.

For non-NPE, I enable MSVS exception-debug to help me locate the bug.

I feel the Aplication_UnhandledException even handler doesn’t help much. It does get triggered when I “throw”, but I still get blank screen.

SL – how to grab dispatcher, random tips

Q: how many dispatchers are there in one SL process?
%%A: 1, according to many c# guys. However, a lot of literature mentions “a dispatcher”

Q: can you get hold of the dispatcher from Any thread Always?
A: http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/ says not always

Q: which source is best to get the dispatcher?
A: Deployment.Current.Dispatcher is preferred over Application.Current.RootVisual.Dispatcher. See http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/ and other sites

Q: Is SynchronizationContext better than dispatcher?
A: http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/ says dispatcher is easier
A: http://dotnetslackers.com/articles/silverlight/Multithread-Programming-in-Silverlight-4.aspx demonstrates both.

Q: how many UI threads are there?
%%A: 1, according to many c# guys.

icon in SL-OOB causing silent death


I realized if the icon.png is zero-byte, then a SL OOB will fail with inconsistent behavior. Launched from the desktop shortcut, blank screen would show up. From MSVS, F5 or Ctrl-F5 would show no screen no error no log even if you enable exception debugging. Even the constructor in App.xaml.cs won’t get invoked.

user-editable XML config file for silverlight OOB app

Requirement: user-editable XML config file (like app.config or yourAppName.config) to control my silverlight OOB app.

Solution: Here are the key steps based on http://www.mohamedibrahim.net/blog/2010/01/27/creating-and-using-silverlight-app-settings-webconfig-configuration-applicatioin-settings-to-change-wcf-service-address-after-deployment-servicereferencesclientconfig-servicereferences-clientconfig/

1) move your app.config content into ServiceReferences.ClientConfig. This file is editable post-install, unlike the app.config which gets converted to binary and embedded in the DLL during build-deploy.

The blog above describes how to pragmatically parse the xml config — nothing fancy.

2) After the install (using sllauncher), you can easily locate the xap file. On my winXP PC it’s in C:\Documents and Settings\myLogin\Local Settings\Application Data\Microsoft\Silverlight\OutOfBrowser\1352946853.theOriginHostname

C:\Users\a5113359\AppData\Local\Microsoft\Silverlight\OutOfBrowser on my win7.

As you would expect, this xap gets overwritten whenever you re-install (with sllauncher). This is one way to confirm any code change took effect.

3) edit the ServiceReferences.ClientConfig file inside the xap. The blog above describes the technique. Actually no need to rename. Just use 7z to open the xap.

4) restart the OOB app. See new config value.

install SL-OOB app by xcopy

Based on http://www.silverlightshow.net/items/How-to-distribute-a-Silverlight-OOB-Application.aspx

In short, install the XAP file via sllauncher.exe.

Q: What files are needed?

%%A: nothing but the XAP file. The MSVS project build creates the XAP in the Bin/Debug folder. You can give it to users.

Q: Can I send the file(s) to a user by email attachment?

%%A: I think so. User need to have Silverlight installed.

Q: User needs to go online?

A: no

Timer to edit UI objects – WPF

http://www.silverlightshow.net/items/Tip-Asynchronous-Silverlight-Execute-on-the-UI-thread.aspx shows a common scenario. Say you want to periodically call WCF and in the callback method update UI directly — by editing UI objects. Not good practice, but sometimes this is quick and dirty.

Solution: System.Threading.Timer, which uses background threads in the per-Process thread pool. Unfortunately these threads aren’t allowed to edit UI objects (only UI thread can). Result — blank UI.

Solution: this.Dispatcher.BeginInvoke(), but how do you get this.Dispatcher? Well, every UI object has a property this.Dispatcher, but is it easy to get a handle on the UI object?

In my case, WCF callback method is part of a static class. In this callback I raise an (static) event. One of the View Model objects subscribe to it. However, the View Model object should not have a handle on the UI objects, by OO principle.

Solution: the CodeBehind is the melting pot. It is part of the View and has access to every View Model object. So my VM exposes a public property this.Dispatcher which is set by the CB. Dependency injection

2) DispatcherTimer is the popular solution. However you can’t change the timer interval mid-flight.

event/method pairs in WPF

In learning WPF/Silverlight, I had a few confusions that are similar. These confusions probably fall into the same category. In all cases, one class has both an Event and a Method of a similar name. Here are some cases in point.

Tip: On*** is usually a method

1) Method OnPropertyChanged() vs PropertyChanged event
PC is more fundamental than OPC. PC is heart of the familiar INotifyPropertyChanged interface. As a result, wpf developers (like us) are frequently required to raise PC events explicitly. How do we raise? Often in a non-static OnPropertyChanged() method. So /there you are/, the link between PC and OPC.

http://msdn.microsoft.com/en-us/library/ms743695.aspx is an MSDN tutorial showing exactly this OPC/PC pattern.

The authoritative MSDN documentation http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx shows the same pattern except the OPC method is actually named NotifyPropertyChanged.

OPC is not a standard method name dictated by the framework. It’s more of a method naming convention.

2) This case is found in the commanding infrastructure of WPF. Method CanExecute() vs CanExecuteChanged event. Once the event fires[2] and a command source object [3] gets its callback method invoked[1], that callback method internally calls CanExecute() to check if it should paint itself dimmed.

[1] often on the GUI thread.
[2] (by invoking each callback on the inv list),
[3] (eg button)

xaml pretty print

#) You can try the imperfect Format Document command from the Edit->Advanced menu to nicely format your XML document. (http://sidersdd.wordpress.com/2008/04/21/format-xml-in-visual-studio/)

#) http://www.softlion.com/webTools/XmlPrettyPrint/default.aspx is good

#) http://www.corefiling.com/opensource/xmlpp.html can sort attributes but unfortunately removes indents on xaml comments and converts double-quote to single-quote

xmlprettyprint.com is less precise about indent

notepad++ HTML-tidy is broken

CommandSource, briefly

Update: it looks like Command Source is usually a user input thingy?

Buttons, MenuItems, Hyperlinks, KeyGestures are command source objects. A command source Instance is a (typically) stateful object. Users issue commands via a command source.

Technically, CommandSource objects are instances of ICommandSource (ICS). It’s revealing to examine the properties of ICS….

Besides the ICS properties, the most important thing to Keep in mind is that Command Source objects subscribe to CanExecuteChanged events, by adding a (2-pointer) delegate instance into the invocation list (behind the event pseudo-field) inside the command object.

What a mouthful! Let’s try again. An event is a (pseudo) field inside a command. The command object “fires event A” by invoking callbacks in A’s invocation list. Each command source instance bundles “this” and one of its non-static methods into a callback object and appends it to the invocation list. Event A is the “CanExecuteChanged” event.

When a command source gets called back up on this event, it queries the command’s CanExecute() and gets a yes/no, and disables/enables itself accordingly. Note in a simple commanding usage, this even never fires and CanExecute() always returns true.

to-target ^ to-source updates in WPF binding

(Based on P502 [[Pro wpf in c#2008)

The fulcrum of MVVM is data binding. Data binding links 2 objects — Source and Target objects.

Rule 1: Source-to-Target is always immediate, in either one-way or two-way. In contrast, T-to-S is not always immediate.

Rule 1a: regular one-way is immediate, since regular one-way means S-to-T. OneWayToSource is like the  T-to-S  in two-way. See below.

Rule 2: In two-way, the immediacy of update is asymmetric.

– Source changes immediately fire events and hit Target object (usually a visual).
–  T-to-S  update mode in two-way set-up has several enum values, such as

** every key stroke
** on focus loss

Intuitively, LostFocus is more reasonable than key-stroke for a text input source. You don’t want event firing on every text box keystroke.

wpf data template, basics

DT is mostly used with collections, though it can be used for standalone objects. Let’s suppose we have a list  box of  Persons.

DT is a chunk of xaml code. (Can it be done in c# code? I have not seen any.). The list box is another chunk of xaml. You could embed the DT chunk in the listbox chunk, but it’s more common to define a “reusable” DT inside a resource dictionary (another chunk of xaml) and give it a name like MyDT. To use this DT, we assign MyDT as the RHS to ItemTemplate property (LHS) of our list box.

In Smarty, a newsletter template would need $yourName, $yourAddress and other dummies. Similarly, our DT chunk includes things like “{Binding path=Address}”. This is a data field, presented within a bunch of container visual controls. Therefore, a DataTemplate precisely describes a (hierarchy of) container holding one (or more) data item.

The same template is repeatedly applied to the Address field (+ other fields) of each list item, to “present” each item on screen.

dependency-property internals – educated guesses

The POCO property is implemented by a backing field. Now (Reason to become obvious) let’s suppose the backing field is in a base class B. Both subclasses C1 and C2 expose some property on that backing field. If there’re 33 C1 instances and 44 C2 instances, then we have 77 of this backing field in memory.

For a DProp “IsDefault” in a Button class, the backing store (there must be one) is in some base class, but there’s no field named anything like “_IsDefaultField”. Rather, I guess all DProp data for the Button class is consistently, generically stored (similar to javascript or perl objects) in some hash table, where

* value — probably nothing fancy — a bool if the DProp should be bool
* key — a combination of the actual class (Button in this case) + the value’s type + the DProp name + …

For a Button instance in memory, if there are 80 DProps, then the hash table in the base class has, logically, 80 key/value pairs.

For a Label instance in memory, if there are 70 DProps, then the hash table in the base class has, logically, 70 key/value pairs.

Given 22 Buttons and 33 Labels on a screen, we have 55 hash tables. Logically, we can safely assume one hashtable per DependencyObject.

Without going any further, let’s step back and ask “Is this design enough to implement basic POCO property?” Basically setter/getters. I would say yes.

In reality we achieve memory efficiency because the hash tables are sparse. Out of the 80 DProps in the 22 Buttons, most of the 1760 values are defaults. All the default values are “removed” from the hash tables. http://stackoverflow.com/questions/7137291/how-does-the-wpf-dependency-property-design-save-memory-consumption and
http://stackoverflow.com/questions/9463216/how-dependency-property-holds-value have concise explanations.

Now, in this design the getter/setter have power features when used in conjunction with the “Hollywood registry” — Each of the 80 DProps in a Button is registered with the “Hollywood”. Therefore when the getter/setter runs, the Hollywood intervenes. Most important power feature is change notification. Overall, this Hollywood is still a mystery to me.

silverlight – Boris

SL runs on both client machine and server machine. SL always needs a serverside. Server must be windows, usually IIS, but can also be WCF services hosted in WinServices or consolt hosts.

SL can run standalone outside a browser, but is usually run inside a browser.

You write SL just like you write WPF. Rather different from ASP

wpf triggers, first lesson

I believe
– property triggers — live inside a style including embedded control template
– data triggers — live inside 1) data templates 2) styles, or a 3) control template embedded in a Style.
( Note data template only accepts data triggers, not property triggers.  See http://stackoverflow.com/questions/17598200/datatrigger-binding-in-wpf-style )

Triggers are predominantly created in xaml. It’s possible to do it in c#, but rare.

Triggers are all about Visual-effects. All these triggers modify the properties of visuals.  PTriggers watch properties; DTriggers watch data; ETriggers watch …

Most common trigger is the property trigger. 2 other common types are Data trigger and Event trigger.

It’s best to internalize one simple property-trigger usage, before looking at advanced triggers. As seen below (example from [[wpf  succinctly]]), you can have 2 triggers on a visual. The 2 triggers can hit the same visual Property like the background color, but only one trigger will fire.

Different aspects (properties) of the visual can be managed through different setters within a Singel trigger. Each setter sets one (depedency) property to control one aspect.



xaml code behind

Each xaml file describes the components, layout, data binding, event-handler and command binding associated with the visual components. The *.xaml.cs file is the code behind file, implementing among others, the event-handlers mentioned in the xaml.

The listeners don’t have to be part of an interface. It is probably mandatory to take 2 inputs — source and event.

C# event registration – unregister first (defensive)

Experienced c# guys have a defensive habit like

Register(Action theDeletage){
  this.someEvent -= theDelegate;
  this.someEvent += theDelegate;

Why the first line? It basically says “first check if new joiner is already in the inv list and remove it if present, then add him to the end”. Remember the inv list is duplicate-allowed. Therefore this defensive practice becomes important when you call Register() repeatedly (esp. in a loop), potentially passing in the same delegate objects over and over.

Without this insurance, the inv list would contain growing duplicates entries. Consequence? Event firing would trigger a large number of duplicate callbacks. I learnt this lesson the hard way.

PropertyChanged events work with a property !! a field (c#

PropertyChanged(this, new PropertyChangedEventArgs(“Age”)) // required by INotifyPropertyChanged

If Age is a field rather than a property in a Model or ViewModel class, then this event firing will fail to have any effect.

Incidentally, event firing and callback happen on the same thread — sequentially, like JTable fireXXX() and unlike invokeLater().

Further, I think the binding system invokes get_Age() and never reads the Age field so even if the field never triggers any event, it will break because initial query-then-display will display an empty string.

DependencyObject ^ DependencyProperty, briefly

I’m sure there are good online articles, but here’re my own 2-cents.

The 2 class names show an implicit connection. A DObj instance has (non-static) method SetValue()/GetValue(), which use the special per-instance hash table to manage the DProp values. These values “describe” that DObj instance in various aspects.

I feel the 2 “constructs” are symbiotic.

[[Pro WPF & Silverlight MVVM]] covers DObj/DProp in details.

PropertyChanged() event firing should use dispatcher

In my app, most of the time I could simply call PropertyChanged() to raise a given event but sometimes this has no effect on GUI (no errors either!) and I have to wrap it inside Dispatcher.BeginInvoke(() => {…})

This is probably because the call to PropertyChanged() happens to be on a non-UI thread. Therefor I added a defensive

protected void BeginInvoke(Action action){
  if (this.Dispatcher == null) throw new Exception(“”);

  if (this.Dispatcher.CheckAccess())
    this.Dispatcher.BeginInvoke(() => { action(); });

listBox ^ listView ^ itemsControl

Inheritance – ItemsControl begets ListBox, which begets ListView.

From IC to ListBox — ListBox adds selection support (single/multiple/Extended)

LV is often used for multi-column table.
LB is usually used for single-column “table”, aka list. Therefore many simple tutorials use LB.

Both LV and LB present the data items readonly by default.

If you need no scrolling, you may not see a border around a listbox. But You can always select each item in it.

http://www.wpfsharp.com/2012/03/18/itemscontrol-vs-listbox-vs-listview-in-wpf/ points out
Sizing — IC is inflexible.
Scrollbar — not in IC

central features of WPF

After studying (50%?) of the most popular wpf features at a superficial level, I now feel at the “center” of the features are
– data binding from VM to visuals
– DProp

Many important features grow (extend, borrow) from the center
– 2-way data binding
– binding from visual to visual
– data triggers
– property triggers? based on DProp
– AProp? based on DProp
– command binding? borrows from data binding
– Most controls rely on data binding
– Most controls expose a lot of dependency properties, and these are easily programmable in mere xaml
– a huge variety of requirements are now achievable in xaml without any c# code, largely due to the simple ideas in the “center”.

itemsControl.Items ^ ItemsSource ^ itemsCollection

Any time you have a collection to show, ItemsControl and subtypes ListBox/ListView are the most popular choices. ItemsControl.Items is a property, whose type is ItemsCollection. By the way, ItemsCollection is a subtype of CollectionView — sorting, filter etc.

For Data binding, the target must be this.ItemsSource, not this.Items. Once using that, Items.Add() will trigger *runtime* exception. Instead, add to the data-bound physical collection instead. That collection is usually an ObservableCollection. After you add to it, the screen will auto-refresh, without any intervention.

Under the hood, I believe After the add/remove, the data binding engine queries the physical data and refreshes the display. Just put a breakpoint on the getter of the added item.

"events" in wpf – 3 meanings

In WPF, the “event” word takes on multiple meanings. Know the subtle differences.

1) CLR event — used extensively in INPC. These events are generated by code, not user actions. Here “event” has the unique dotnet meaning. In other GUI systems (like swing), events are also generated from code, such as table change event after you add a row.

2) UI event from keyboard/mouse — the traditional GUI events, implemented (in WPF) with the CLR event + other things. These events have a hardware flavor.

3) routed (bubble/tunnel) event — a special type of UI events?

xaml code behind – phrasebook

Views — only views can have a code behind.
Behind — a view. The code exists Behind a view

*.cs sits behind *.xaml — code behind is a someName.xaml.cs file, behind a someName.xaml file

fields — defined in the xaml are directly accessible as Instance fields of the code behind class.

Part of the view — the code behind class is part of the view, not the VM or M.

event registration — often registered in xaml or (programmatically) in the code behind.

data binding?

silent bug if u forget to implement INotifyPropertyChanged

public int PortNumber{
    return _portNumber;
    if (_portNumber != value){
      _portNumber = value;

If host class Agent implements INotifyPropertyChanged, then the wiring works as follows
#1) users click a “++” button
#4) event handler increments PortNumber and saves it via the setter
#6) setter fires prop changed event
#9) xaml binding system queries PortNumber property via getter — you can see this in a debugger

Now things break if you don’t implement INPC. Xaml binding doesn’t call the getter (#9) and won’t display new value, even though
– event firing still happens (#6),
– xaml won’t complain either

I think xaml will still bind to this Agent object, but won’t treat Agent as a “Notifying source”, so the binding system will ignore the event — the invitation to re-query the VM for updates.

SL WCF async call – a real example

In one of my SL apps, client need to
1) connect (via ConnectAsync/ConnectCompleted) to a WCF server so as to subscribe to a stream of server-push heartbeat messages. These heartbeats must update the screen if screen is ready.

2) client also need a timer to drive periodic pings using getXXXAsync/getXXXCompleted. If ping succeeds/fails, we would like to update the status bar. Therefore the callbacks had batter come after screen setup.

3) at start time client makes one-time get1Async/get1Completed, get2Async/get2Completed, get3Async/get3Completed calls to receive initial static data so as to populate the GUI. I wrapped these calls in a static Download6() method.

*) basically all these data from server (either server-pushed or callbacks) “WANT” to update screen provided static data is loaded, which is done by D6 callbacks. So D6 callbacks had better happen before heartbeats come in, or heartbeat processing would hit empty static data and cause problems. Also, D6 callbacks must execute after screen setup, because those callbacks need to update screen.

That’s basically the requirements. In my initial (barely working) solution everything except timer stuff happens on the main thread.

1) at start time, main thread invokes D6. The callbacks would come back and wait for the main thread to execute them — troublesome but doable
2) main thread makes initial ConnectAsync. The callback would hit main thread too
3) before these callbacks, main thread finishes painting the screen and setting up the view model objects.
4) now the D6 and ConnectCompleted callbacks hit main thread in random order. D6 callbacks tend to happen before server pushes heartbeats.
5) upon ConnectCompleted, we subscribe to heartbeats
6) Timer has an initial delay (about 10s) so usually starts pinging after the dust settles. The Async and Completed calls execute on 2 different non-main-threads.

All the “scheduling” depends on event firing. It’s not possible to “do step 1, then at end of it do step 2…” on main thread.

I now prefer to move the connect, d6 etc off main thread, so the callbacks would hit some other threads. More importantly, this way I have a chance to utilize locks/wait-handles/events to properly serialize the Get/Connect calls, the timer-start and the subscription to server-push heartbeats. This means Step B starts only after Step A completes all callbacks. This was not possible earlier as it would block the main thread and freeze the screen.

WCF async call in SL – 2 funny rules

Rule AB0) in all cases, Main thread must not be blocked during the WCF call. Some part of the flow must happen on the Main thread.[1]

A) You can make an xxxAsync call from either Main thread (Thread1 in debugger) or a non-Main-thread such as thread pool or timer.

Rule 1) Main thread will execute xxxAsync(), then finish whatever it has to do, then execute the callback when it becomes idle. The callback ALWAYS executes on the same Main thread.

Rule 2) non-Main thread executes xxxAsync(), then the callback usually executes on the same (or another) non-main-thread.

B) Synchronous? It took me a bit of effort to make the call synchronously. But obey Rule AB0. See http://www.codeproject.com/Articles/31018/Synchronous-Web-Service-Calls-with-Silverlight-Dis

 var channelFactory = new ChannelFactory("*");
var simpleService = channelFactory.CreateChannel();
var asyncResult = simpleService.BeginGetGreeting("Daniel", null, null);
string greeting = simpleService.EndGetGreeting(asyncResult); 

I find it a good rule to avoid calling xxxAsync on Main thread in non-trivial SL apps. I now do it on other threads. It often involves more BeginInvoke, but eliminates a lot of future restrictions.

Incidentally, if the callback is on non-Main thread but needs to modify View or Model, then you need to use BeginInvoke or SynchronizationContext

[1] Suppose you put UI thread on some wait handle or grabbing a lock so it blocks, to be released by the “wcf thread”. If you do that, then “wcf thread” would also block waiting for some part of the processing to run on the Main thread. This is a fairly classic deadlock situation.