500 likes | 645 Views
Developing Windows and Web Applications using Visual Studio.NET. Drew Robson. Homework?. Session 5: WCF and Multi-Threading. What are Web Services? WCF Services Consuming Web Services Threading Do the lab Review. Web services. Web services. "Call a service over the web"
E N D
Developing Windows and Web Applications using Visual Studio.NET Drew Robson
Session 5: WCF and Multi-Threading • What are Web Services? • WCF Services • Consuming Web Services • Threading • Do the lab • Review
Web services • "Call a service over the web" • A Service provides information • Consumable by software
What are Web Services? • Collection of protocols and standards • Exchanging data between applications or systems Software/Applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks
What are Web Services?Con'd • The technologies that underpin Web Services are • XML • SOAP (Simple Object Access Protocol) • This is a way of sending around objects over a network • Cross Platform e.g. • Java Web Service (AXIS) can be consumed by a .NET application and vice versa
Public Web Services • There are many public web services available on the Web, and there are Web Services APIs for popular applications such as: • Google http://code.google.com/apis/ • Amazon http://en.wikipedia.org/wiki/Amazon_Web_Services • Facebookhttp://developers.facebook.com/ • Virtual Earth http://msdn2.microsoft.com/en-us/virtualearth/default.aspx • Microsoft, new to the party with Azure: http://www.microsoft.com/azure/default.mspx • More here • http://www.service-repository.com/
WCF • Building block for building Connected Systems • Designed around messages! • Support for all standards/specifications around messaging (particularly driven by WS-*) • Consistent API regardless of messaging requirement
Not just “Web Services” • Supports variety of transport and encoding configurations • Messaging standard is SOAP but this is not the only option • Extensibility model allows for any custom requirements/encoders/channels to be developed
Windows Communication Foundation (WCF) • Supports transport protocols, • HTTP Web services • UDP User Datagram Protocol • TCP Transmission Control Protocol • Supports • Queues MSMQ (Microsoft Message Queue) • Transactions • Reliable sessions • Better security model http://prezi.com/tg2kaukw8sez/wcf-intro/
Definitions • Address where the WCF service is available from • Binding how to get access to the WCF service • Contract what the WCF service can do • Behavior how the service will behave locally (e.g. debugging)
Creating a WCF Service • Built in WCF Service Project • Define the service with ServiceContract • Define methods with OperationContract
Define an Interface contract • Contract(IService.cs) It means INTERFACE
Implement the contract • Contract • Implementation
Consuming Web Services • Automatic - Add a Web Reference to your client • Dynamically generates a web service client class with all the exposed methods • Synchronous and Asynchronous methods • Silverlight:All web service method calls are Asynchronous
WCF Service Demo (The LAB) • Creating • Consuming • Configuring
Threading • Why do we need threading? • Blocking calls (e.g. Disk IO, Network) on long running-tasks • Responsive User Interface (UI) • E.g. Windows Desktop Search • Better performance (especially on multi-core processors)
Processes • Application can spawn one or more processes • Processes have isolation, separation of • Data • Memory • Resources • Processes contain Threads
Threading and the O/S • Windows is a Pre-emptive multitasking operating system • OS is responsible for managing time slices (quantums) between different processes • OS Kernel switches/schedules execution code between threads
Threading in .Net • System.Threading • Background Worker • “Threadsafe” classes (particularly collections) • Thread Synchronisation • Interprocess communication • AppDomain
Important Concepts • Updating UIUI Elements are only accessible from the UI thread • Some classes are "not Threadsafe""Not Threadsafe" means class is NOT synchronizing multi thread access Data overwritten or corrupted (e.g. Data collections) • Order of executionCannot predict the sequence when separate threads will finish their work
What is STA (and what happened to MTA?) • Single thread apartment (STA)
Threading in WinFormsFrom Bad to Good • Application.DoEvents • System.Threading • Thread.Start • Delegate.BeginInvoke • BackgroundWorker component
Application.DoEvents() • Call this method inside long running code that is being processed • What it does is it issues a command to the UI to process pending events on the message queue e.g. • Mouse Clicks • Redraw Window etc
Application.DoEvents() Worker 1 SearchGoogle() UI Return FetchData Worker 2 Merge SearchYahoo() Done Return
DoEvents is Bad! • Do Events processes all Window Messages in the queue until it has run out of messages (click, paint, focus, etc.) • In an example of loading a Listbox with items: • What happens if the user clicks the close button? Ooops! IndexOutOfRangeException! Clicking on the close box has invoked the form’s Dispose method, which has cleared the control collection. What's worse is that clicking close on the form didn't stop the list box processing from finishing up - while the form was no longer visible, this handler was merrily keeping the application alive. • Why wouldn’t this normally happen? The action of the user pressing the close button would not be processed until you’ve returned from the handler for the button click.
GOOD BAD usage of DoEvents • Application.Run • Process mouse up on button • Fire ButtonClick event • Add some items to listbox • Call Application.DoEventsto make it look more responsive • Process mouse up on close box • Dispose the form • Add remaining items to listbox • Update the first control on the form -- BOOM! Controls collection has been cleared! Application.Run Process mouse up on button Fire ButtonClick event Add bunch of items to listbox Update the first control on the form Process mouse up on close box Dispose the form
An Easier Way • BackgroundWorker Component • Sites to Research • http://msdn2.microsoft.com/en-us/library/system.componentmodel.backgroundworker(vs.80).aspx • http://www.codeplex.com/ExerciseBackgroundW • http://www.codeguru.com/columns/vb/article.php/c10755/
Synchronising User Interface Synchronization problem solved in VS 2005 (and later) by only allowing the main UI thread to access UI controls Worker threads must tell the UI thread to make a change on their behalf via event
Background Worker Component • Makes life easy in .Net! • No complex code needed only need to implement a few methods: • DoWork • RunWorkCompleted • ProgressChanged
The One Golden Rule When Multiple threads access a shared resource, only 1 thread can update it at a time Otherwise we get: • Deadlocks • Race Conditions Correct use of Synchronisation prevents these situations
Synchronization & Shared Resources Synchronisation involves controlling access to a shared resource so only one thread can access the resource at a time. Resources include: • Variables e.g. Arrays • User Interface Controls e.g. Progress Bar
Other .NET multi-threading Technologies and Concepts • Windows WorkFlow (WF) parallel task execution • WF is explcitly designed for long-running tasks • PLINQ (Parallel Linq) .Net 4.0 • UI Control Virtual Mode • You control how the data is retrieved into the control when it needs to display • Use this if you have a 1 million rows in memory, but can only display 50 at a time (similar to paging in a webform)
A Real World Example SSW Link Auditor
Link Auditor • Threading was used to achieve • A responsive UI throughout • Optimize the scanning process • Techniques that we used • Delegates and Callbacks • ManagedThreadPool class
Resources • Threading in .NET • http://www.albahari.com/threading/ • Tip! - Keyboard shortcuts • http://www.itscodingtime.com/post/Visual-Studio-2010-Keyboard-Mouse-Shortcuts.aspx
Resources - N-Tier apps • LINQ to SQL vs LINQ to Entities • http://stackoverflow.com/questions/2443836/what-is-the-differnce-between-linq-to-entities-linq-to-sql-and-linq-to-data • http://www.ssw.com.au/ssw/Standards/Rules/RulesToBetterLINQ.aspx#WhyLINQtoEntitiesNotSQL
Part 1 - Review • .NET • C# • Visual Studio 2010 • LINQ • Databinding • UX (Usability) • Winforms – Best practices • N-Tier applications • Deployment – Clickonce • Security • Web services • WCF • Threading
Part 2 – ASP.NET The web!! • Sign up on http://www.aspnet4.de/ • Yes its german! • But free ASP.NET 4 hosting with SQL Server backend • Use http://translate.google.com/ OR http://www.aspspider.com/profiles/Register.aspx • ASP.NET Quick hit videos • http://www.asp.net/learn/aspnet-4-quick-hit-videos/
Lab Now you!!
2things… • DrewRobson@ssw.com.au • twitter.com/drewmrobson
Thank You! Gateway Court Suite 10 81 - 91 Military Road Neutral Bay, Sydney NSW 2089 AUSTRALIA ABN: 21 069 371 900 Phone: + 61 2 9953 3000 Fax: + 61 2 9953 3105 info@ssw.com.auwww.ssw.com.au