Async Calls in Silverlight and WPF Clients

Info

Breakout Session :: 400 (Expert) :: Developer Tools, Languages and Frameworks

“Whenever doing blocking tasks, particularly service calls in a Silverlight or Windows Presentation Foundation (WPF) client, you will need to make those calls asynchronously. While async calls have been around for a long time in Microsoft .NET, the patterns for addressing them have been changing and improving. This session covers several common patterns for addressing async calls in client applications, including new and emerging approaches to async patterns such as Reactive Extensions that let you treat asynchronous execution like a LINQ collection and the Task-based Async pattern and keywords coming for the C# and VB languages. This session takes the mystery and confusion out of what happens and when — and how to keep your code clean and safe in an inherently asynchronous client world.”

Video

Highlights

This session provided a practical overview of asynchrony from the perspective of the UI (and by extension the affinity that UI objects and ObservableCollection<T> has with the UI thread). Some rule-of-thumb tips are:

  • Never block the UI thread. If it takes longer than 50-60ms, async it.
  • Never access UI objects from a non-UI thread.
  • Don’t access variables from multiple threads with protection.

The asynchronous patterns provided by the .Net Framework are:

  • Begin/End Async Pattern
  • Async/Completed Pattern
  • Task Parallel Library (Task<T>)
  • Task-based Async (async and await keywords)
  • Reactive Extensions (LINQ + Observables + Schedulers)

Links

Demystifying .Net Asynchronous Programming

Info

Breakout Session :: 400 (Expert) :: Developer Tools, Languages and Frameworks

“Asynchronous programming is no longer an option; it’s become a must on various platforms, including Silverlight, Windows Phone 7, and various data-centric frameworks. Unfortunately, dealing with asynchrony is way too hard in today’s world of development tools and frameworks. The huge amount of manual and error-prone plumbing leads to incomprehensible and hard to maintain code. As we reach out to services in the cloud, the desire for asynchronous computation is ever increasing, requiring a fresh look on the problems imposed by reactive programming. In this session, we explore various methodologies to address asynchronous programming, and explain how they relate and differ. First, we’ll explore existing patterns and libraries – such as the TPL – to sketch some of the pain-points. Armed with this knowledge, we’ll approach the problem from different angles, including a language-centric view with F#’s asynchronous workflows and the upcoming asynch and await features in C# and Visual Basic. Next, we’ll move beyond sequential composition of asynchronous computations, and introduce the Reactive Extensions (Rx) that enable you to express rich queries – even using LINQ syntax – over asynchronous push-based “reactive” event streams.”

Highlights

The discussion starts by introducing the concepts of Asynchrony (multiple parties evolving in time independently), Concurrency (order in which multiple tasks execute is not determined) and Parralelism (multiple tasks working together), and some wording (“Reactive”, “Callbacks”, “Events”) that typically describe asynchronous situations.

Abstractions in .Net that support asynchrony are: Asynchronous Programming Model (uses callback functions), Event-Based Asynchronous Pattern (uses completion events), and the BackgroundWorker Component.

New tools and abstractions being introduced in upcoming versions of C# and .Net include:

  • await keyword suspends the code that follows the keyword into a continuation for the asynchronous operation completion. The keyword (and the code following it) can be safely wrapped in standard control statements such as while{}, or try{} catch{} blocks.
  • Task<T> is a representation of computations (.StartNew()), and hooks (.ContinueWith()) for continuations (which allows for sequencing). Task.Result blocks the calling thread.
  • BeginVerb-EndVerb patterned functions and VerbAsync functions are complemented with VerbTaskAsync functions that return Task<T>.

Some code examples:

Example 1

1
2
3
var report = Task.Factory.StartNew(() => GetFileData())
			 .ContinueWith(x => Analyze(x.Result))
			 .ContinueWith(y => Summarize(y.Result));

Example 2

1
2
3
4
5
6
7
8
9
10
11
12
13
async void DoWorkAsync() {
	var t1 = ProcessFeedAsync("x");
	var t2 = ProcessFeedAsync("y");
	await Task.WhenAll(t1, t2);
	DisplayMessage("Done");
}
 
async Task ProcessFeedAsync( string url ) {
	var text = await DownloadFeedAsync(url);
	var doc = ParseFeedIntoDoc(text);
	await SaveDocAsync(doc);
	ProcessLog.WriteEntry(url);
}

Reactive Extension (Rx)

Rx is a library for composing asynchronous and event-based programs using observable sequences. Think IObservable<T> and IObserver<T> (subscribe, push) vs. IEnumerable<T> and IEnumerator<T> (pull, blocking).

The concepts introduced by Rx are best studied through additional research into some of the functions it provides:

  • .Throttle()
  • .DistinctUntilChanged()
  • .TakeUntil()
  • .ObserveOn()
  • .Subscribe()

The relationship between the various paradigms is best visualized on a graph representing (Axis Y): Single Value vs. Multiple Values over (Axis X): Syncrhonous vs. Asynchronous … the four distinct quadrants of this graph are:

  • Single-Value Synchronous: Func<T>
  • Single-Value Asynchronous: Task<T> (and await)
  • Multiple-Value Synchronous: IEnumerable<T>
  • Multiple-Value Asynchronous: IObservable<T> (and .Subscribe())

MVC, MVP & MVVM: Comparison of Architectural Patterns

Info

Lunchbox Session :: 300 (Advanced) :: Developer Practices

“This session compares the architectural patterns of Model-View-Controller (MVC), Model-View-Presenter (MVP) and Model-View-View Model (MVVM). Each pattern creates testable, maintainable and reusable application components, however, there are differences that suit each approach to specific types of developer tooling. The presentation first looks at the basic theory and differences between the approaches; then uses demos that show how each apply to Microsoft ASP.NET, Microsoft Silverlight/Windows Presentation Foundation (WPF) and Microsoft SharePoint developer application projects.”

Video

Highlights

The MVC pattern is distinct in that the user interacts directly with the Controller objects, while both others represent patters where the user interacts with the View objects. MVC is primarily suited for use in the ASP.Net MVC Framework, as the underlying concepts are fundamentaly built in to the framework itself. With some effort however, MVC can be implemented directly onto standard ASP.Net (which is of course what the MVC Framework essentially does for you). WinForms applications could also fit into the MVC paradigm, and can be built on this pattern with even less effort than standard ASP.Net. In this pattern: M = Model, V = View and C = Controller; where M is unaware of V and C, V is aware of M, and C is aware of both V and M.

MVP lends itself well to “standard” ASP.Net projects and SharePoint development, with the assumption (and indeed “requirement”) that while Views are the point of entry and interaction with the user, they “dumb [themselves] down” and relinquish control to the Presenters that they instantiate. In this pattern: M = Model, V = View and P = Presenter; where M is unaware of V and P, V is aware of P, and P is aware of both M and an interface representative of V.

MVVM is the most recent evolution of these “separation of concern” patterns, and is most useful in the XAML (Silverlight and WPF) environment, which has strong data- and command-binding support. Similar to MVP, Views in MVVM also defer all business logic to the ViewModel. Communication between View and ViewModel is facilitated through a combination of Command Bindings and Events (behaviour-driven communication) and Data Binding (data-driven communication). In this pattern: M = Model, V = View and VM = ViewModel; where M is unaware of V and VM, V is aware of VM, and VM is aware of M.