Professional ASP.NET Web Services : Asynchronous Programming

Similar documents
The contents of this document are directly taken from the EPiServer SDK. Please see the SDK for further technical information about EPiServer.

Event-based Asynchronous Pattern Overview 1 Implementing the Event-based Asynchronous Pattern 5 Deciding When to Implement the Event-based

Asynchronous Programming Model (APM) 1 Calling Asynchronous Methods Using IAsyncResult 4 Blocking Application Execution by Ending an Async Operation

Web Services in.net (2)

Web Services in.net (6)

C# Asynchronous Programming Model

Sri Lanka Institute of Information Technology System Programming and Design II Year 3 Tutorial 06

Tutorial 5 Completing the Inventory Application Introducing Programming

Classes in C# namespace classtest { public class myclass { public myclass() { } } }

Web Services in.net (6) cont d

การสร างเว บเซอร ว สโดยใช Microsoft.NET

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects

Patterns for Asynchronous Invocations in Distributed Object Frameworks

Chapter 1 Getting Started

In order to create your proxy classes, we have provided a WSDL file. This can be located at the following URL:

Tutorial 6 Enhancing the Inventory Application Introducing Variables, Memory Concepts and Arithmetic

OGSI.NET UVa Grid Computing Group. OGSI.NET Developer Tutorial

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Developing Microsoft Azure and Web Services. Course Code: 20487C; Duration: 5 days; Instructor-led

Do not start the test until instructed to do so!

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Contact information: Aanderaa Data Instruments AS PO BOX 34, Slåtthaug 5851 Bergen, NORWAY TEL: FAX:

Definition: A thread is a single sequential flow of control within a program.

BEAWebLogic Server. WebLogic Web Services: Advanced Programming

THREADS AND CONCURRENCY

Java Programming Constructs Java Programming 2 Lesson 1

CS193k, Stanford Handout #8. Threads 3

Chapter 4: Processes. Process Concept. Process State

Lecture Notes on Programming Languages

The Network. Multithreading. This tutorial can be found on -

Operating Systems (234123) Spring (Homework 3 Wet) Homework 3 Wet

Developing Microsoft.NET Applications for Windows (Visual Basic.NET)

Interprocess Communication

Software Paradigms (Lesson 10) Selected Topics in Software Architecture

CS 351 Design of Large Programs Threads and Concurrency

Multiple processes can run in parallel on a single computer and multiple threads can run in parallel in a single process.

Item 18: Implement the Standard Dispose Pattern

Part V. Process Management. Sadeghi, Cubaleska RUB Course Operating System Security Memory Management and Protection

IBD Intergiciels et Bases de Données

Supporting Class / C++ Lecture Notes

Asynchronous Method Calls White Paper VERSION Copyright 2014 Jade Software Corporation Limited. All rights reserved.

Lesson I2C. I²C (Inter-Integrated Circuit) Lab Assignment: I2C Slave Driver

Developing Web Applications Using Microsoft Visual Studio 2008 SP1

Introduction to Programming Using Java (98-388)

Chapter 13 Working with Threads

Operating System Support

05. SINGLETON PATTERN. One of a Kind Objects

Unit 20: Extensions in ActiveBPEL

Objectives. Introduce static keyword examine syntax describe common uses

Threads are lightweight processes responsible for multitasking within a single application.

Actor-Based Concurrency: Implementation and Comparative Analysis With Shared Data and Locks Alex Halter Randy Shepherd

5.4. Events and notifications

CS333 Intro to Operating Systems. Jonathan Walpole

VuGen.NET Protocol Recording Best Practices and Troubleshooting

CS514: Intermediate Course in Computer Systems

COSC 2P95 Lab 9 Signals, Mutexes, and Threads

Course Syllabus: In-Depth unipaas Programming Techniques

7. System Design: Addressing Design Goals

Software Architecture Patterns

Pace University. Web Service Workshop Lab Manual

THREADS & CONCURRENCY

Decisions: Logic Java Programming 2 Lesson 7

CE221 Programming in C++ Part 1 Introduction

Developing Microsoft.NET Applications for Windows (Visual Basic.NET)

Asynchronous Programming Demystified

/* Copyright 2012 Robert C. Ilardi

Introduction. In this preliminary chapter, we introduce a couple of topics we ll be using DEVELOPING CLASSES

Contents. Java RMI. Java RMI. Java RMI system elements. Example application processes/machines Client machine Process/Application A

1 Shyam sir JAVA Notes

CS510 Operating System Foundations. Jonathan Walpole

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Electronic Payment Systems (1) E-cash

Concurrency Abstractions in C#

The Microsoft.NET Framework

Chapter Outline. Chapter 2 Distributed Information Systems Architecture. Layers of an information system. Design strategies.

Chapter Outline. Chapter 2 Distributed Information Systems Architecture. Distributed transactions (quick refresh) Layers of an information system

Distributed Systems Project 4 Assigned: Friday March 20 Due: Friday April 3, 11:59pm

Distributed Collaboration - Assignment 1: Multi-View 1-User IM

You can call the project anything you like I will be calling this one project slide show.

Pace University. Fundamental Concepts of CS121 1

Virtual Machine Design

MCSA Universal Windows Platform. A Success Guide to Prepare- Programming in C# edusum.com

Part Two - Process Management. Chapter 3: Processes

THREADS & CONCURRENCY

Replication. Consistency models. Replica placement Distribution protocols

Basic Properties of Styles

Configuring, Managing and Troubleshooting Microsoft Exchange Server 2010

Flag Quiz Application

Migrate Your Skills to Microsoft.NET Framework 2.0 and 3.0 using Visual Studio 2005 (C#)

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Notes based on prof. Morris's lecture on scheduling (6.824, fall'02).

XML Web Services Basics

THE UNIVERSITY OF WESTERN AUSTRALIA SAMPLE EXAM QUESTIONS 2007 WITH SOLUTIONS SCHOOL OF COMPUTER SCIENCE CITS3213 CONCURRENT PROGRAMMING (PART II)

C++ for Python Programmers

Tutorial 8 Build resilient, responsive and scalable web applications with SocketPro

Integration Best Practices: Net Change Design Patterns

Refactoring Without Ropes

Transcription:

Professional ASP.NET Web Services : Asynchronous Programming To wait or not to wait; that is the question! Whether or not to implement asynchronous processing is one of the fundamental issues that a developer must answer when invoking function calls across process boundaries. Given that the option to invoke an asynchronous call is available, the programmer has to weigh the relative ease of coding synchronous calls with its inherent drawback - when a synchronous call is made, the calling thread is blocked and has to wait until the function completes. In many instances, this is an acceptable shortcoming, as in the case when a program's logic flow should not continue until data is retrieved from a database. Asynchronous processing, on the other hand, allows more parallelism. A thread that initiates an asynchronous call is not blocked and can therefore do almost any computation while the method is in transit. The case for asynchronous processing becomes very compelling in the enterprise computing space where systems need to handle hundreds of thousands of function call requests and synchronicity may become a barrier to scalability. Web Services support both synchronous and asynchronous communication between the client application and the server hosting the service. Since both are supported, the developer is challenged with deciding which type of process to initiate in their application. In this chapter, we're going to dive into the subject of synchronous and asynchronous programming as it pertains to ASP.NET Web Services. We'll explore the mechanics of invoking Web Services via an asynchronous mechanism. We'll also look into the.net framework and how it provides the infrastructure for asynchronous processing. So, the topics for this tutorial are: Synchronous versus asynchronous invocations Asynchronous design patterns in.net How to invoke Web Services asynchronously Synchronous Versus Asynchronous Invocations : In this section, we'll compare the merits and shortcomings of both the synchronous and asynchronous approaches to calling Web Services. We'll also learn how to actually develop client applications that make use of the asynchronous mechanisms built into the.net framework. This will set the stage for a deeper discussion of asynchronous processing in the subsequent sections. 1

The Case for Synchronous Processing : Synchronous operations consist of component or function calls that operate in lockstep. A synchronous call blocks a process until the operation completes. Only then will the next line of execution be invoked. There are many examples in life that model this pattern of behavior. The cafeteria line at your local restaurant, for example, behaves in a synchronous fashion. Customers are serviced one at a time. While they are in line, they are blocked from conducting other activities, and they wait until all their food choices are served before they can continue with their lunch-break. Of course, after waiting for a very long time they might give up and leave. As you can see, the procedure for making synchronous calls is straightforward: 1. The client obtains an interface pointer to the server object and calls a method through that pointer 2. The client waits until the server either completes the method call, or if there is no response for a given period of time the client raises an error 3. Only after the method call returns is the client free to continue with its processing It is this simplicity that makes synchronous processes a compelling choice. Most of the time, the performance achieved from method calls is acceptable and does not warrant the extra overhead required for concurrent processing. In fact, most of the function calls in the.net framework are synchronous to minimize problems that can arise from asynchronous message processing. Likewise, the method calls you will be implementing will be done in a synchronous fashion in most cases. Asynchronous message passing, on the other hand, is more difficult to code and introduces several problems. What happens if the method call is not delivered to the server object successfully? The calling process does not wait for delivery of the message, and thus never hears about the error. The operating system has to provide the infrastructure for reporting such errors, or worse, the programmer may have to write special code to handle such cases. Another related problem is how will the calling application discover the completion of the called function? The application will either have to create a polling mechanism, event trigger, or callback method in order to be later notified of the operation. Because synchronous messaging is so easy to implement, you may be tempted to take the simple route and always use a synchronous mechanism when invoking a Web Service from your client code. 2

Consider your choice carefully because this decision will have an impact on how your client application will perform. When implemented properly, using asynchronous communication may improve system usage and avoid delays on the client side, while waiting for the Web Service results. When Asynchronous Processing Is Better : When method calls are invoked across process and machine boundaries via an RPC mechanism, it's oftentimes a likely candidate for asynchronous processing. This is definitely true in the case of Web Services where the remote procedure call is sent via HTTP and must deal with issues such as bandwidth constraints and network latency. What makes asynchronous method invocations a good choice for communicating with Web Services? An asynchronous operation will not block the calling thread, which only initiates the operation. The calling application must then discover completion of the call by polling, by software interrupt, or by waiting explicitly for completion later. An asynchronous operation will need to return a call or transaction ID if the calling application needs to be later notified about the operation. At notification time, this ID would be placed in some global location or passed as an argument to a handle or wait call. The procedure for making an asynchronous call is not as simple as its synchronous counterpart: 1. The client obtains an interface pointer to the server object and calls the method asynchronously. The client includes a function pointer to a sink object for message callback. 2. The call returns immediately and the calling thread is free to execute the next line of code. 3. When the method is finished processing the request, the server notifies the client through the callback routine in the sink object. Even with advancements implemented in the.net framework, successfully developing asynchronous programming logic is not trivial. You need to examine the requirements of your application carefully to determine whether or not the code you're writing can even benefit from asynchronous events. Here are some general guidelines to consider when making your decision: Consider asynchronous processing if the calling thread controls a Windows user interface. In this case, the calling 3

thread can't afford to be blocked during a remote method call because the UI will freeze. Asynchronous processing may help with scalability if the Web Services client is an ASP.NET application or another ASP.NET Web Service. In this scenario, a blocked synchronous call in the code can stall the ASP.NET worker thread, which can force other applications' requests to queue and, therefore, impact scalability. Using asynchronous communication instead could at least free up the threads that ASP.NET isn't using for the Web Service calls. Asynchronous server processing is discussed in detail towards the end of this chapter. If there is a possibility that the remote procedure call to the Web Service may take a while to complete, asynchronous processing may be beneficial. In this case the client application can do other work on the thread before it needs the results from the remote procedure call. The client application may need to make concurrent calls to one or more remote services. In this case, using an asynchronous remote procedure call is much better than spinning off multiple threads to do the same work. For example, if an application needs to make concurrent synchronous calls to three different Web Services, it cannot do so with one thread. It has to spin off at least two threads and make a remote call in each thread. However, if the client uses an asynchronous remote call, it can make all three calls on one thread and then wait for all of them. A Sample Web Service : Now that we've discussed the pros and cons of both the synchronous and asynchronous programming methodologies, let's write some code to illustrate the concepts. We'll begin by creating an ASP.NET Web Service that our client application can invoke. We'll then create two separate applications, with one calling the Web Service synchronously, and the other asynchronously, so that we can compare the techniques of each approach. For the purposes of our discussion, we will be making use of an ASP.NET Web Service that returns a stock quote. The Web Service, named StockService, accepts a ticker symbol parameter that will return a string representing the value of the stock. In order to properly demonstrate asynchronous programming, the Web Service we will be invoking will also have the ability to simulate a longrunning process. For that purpose, the StockService example accepts another parameter that represents the number of seconds the service will wait before returning the stock value back to the calling application. Figure 1 is a screenshot of the StockService.asmx page displaying the GetStockQuote method. 4

Figure 1: StockService Test Page The TickerSymbol parameter will accept a string value representing a stock symbol or a company name. The DelayInSeconds parameter will accept an integer value representing the number of seconds the Web Service will wait before returning the stock's value. Below is the code for the StockService Web Service written in C#. Bear in mind that this Web Service is simply a simulation for illustrative purposes only and obviously doesn't return accurate stock values. The actual algorithm that a production Web Service would use to return a stock's actual value will be much more complex than this example. Listing1 StockService Codes using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; namespace StockService /// <summary> /// Summary description for Service1. /// </summary> public class StockService : System.Web.Services.WebService 5

public StockService() //CODEGEN: This call is required by the ASP.NET Web Services Designer InitializeComponent(); #region Component Designer generated code //Required by the Web Services Designer private IContainer components = null; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) if(disposing && components!= null) components.dispose(); base.dispose(disposing); #endregion [WebMethod] public string GetStockQuote(String TickerSymbol, int DelayInSeconds) //Create a delay to simulate a long-running process if (DelayInSeconds > 0) // Have the thread sleep based on the DelayInSeconds parameter // Note: The constant "1000" is to convert seconds to milliseconds System.Threading.Thread.Sleep(DelayInSeconds * 1000); // Retrieve the stock quote based on the TickerSymbol parameter // NOTE: Stock values are for simulation purposes only string Quote; switch (TickerSymbol.ToUpper()) case "MSFT": Quote = "67"; break; case "SUNW": Quote = "70"; 6

break; case "IBM": Quote = "100"; break; default: Quote = "Unknown"; break; return Quote; The Web Service has one method, GetStockQuote. GetStockQuote accepts the two parameters we previously discussed: TickerSymbol and DelayInSeconds. [WebMethod(Description="Returns a stock quote")] public string GetStockQuote(string TickerSymbol, int DelayInSeconds) The GetStockQuote method returns a string, which represents the value of the requested stock. The method will return a string value of "Unknown" if the stock's value is not known. Additionally, this method has the functionality to delay the delivery of the return message to simulate a long server-side process. The code accomplishes this by retrieving a handle to the current thread and causes the thread to sleep for the duration specified in the DelayInSeconds parameter: //Have the thread sleep based on the DelayInSeconds parameter //Note: The constant "1000" is to convert seconds to milliseconds System.Threading.Thread.Sleep(DelayInSeconds * 1000); Figure2 is the output of the GetStockQuote method when invoked from the sample page provided by ASP.NET: 7

Figure 2: Stock Service Result Page You will notice in our sample Web Service that there is nothing specific in the implementation of StockService that provides asynchronous functionality. It's actually the calling application that will decide if a particular call should be asynchronous. This is in keeping with one of the tenets of the.net framework, which states that it's not necessary for a called object to do additional programming to support asynchronous behavior by its clients. In fact, the called object doesn't even have to be an ASP.NET Web Service. It could be a Web Service developed on another platform and we would still be able to invoke an asynchronous call from a client running on the.net framework. The generated C# proxy class contains both synchronous and asynchronous versions of the GetStockQuote method. The asynchronous version consists of two methods, a BeginGetStockQuote and an EndGetStockQuote method. The BeginGetStockQuote method is used to initiate the call to the Web Service, while the EndGetStockQuote method retrieves the results. We'll take a closer look at this proxy class in the "Asynchronous Programming in.net" section of this chapter. 8

Using the Sample Web Service : Now let's have some fun by invoking this Web Service from a client application both, synchronously and asynchronously. The client will be developed as a console application using Visual Studio.NET. A Sample Synchronous Method Call : The code for calling a Web Service synchronously should be relatively familiar by now, since many of the examples in this book have been synchronous remote procedure calls to Web Services. This example will be no different. Here's the C# code for the console application, SyncStockClient.exe in the bin subfolder of the SyncStockClient folder in the download, that uses the StockService Web Service: Listing2 SyncStockClient Codes using System; namespace SyncStockClient /// <summary> /// Summary description for Class1. /// </summary> class SyncStockClient /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) // // TODO: Add code to start application here // String ReturnValue; // create the web service instance via the proxy class localhost.stockservice objstockservice = new localhost.stockservice(); array arguments service // Make sure there are at least two items in args[] // NOTE: the args[] array contains command line if (args.getupperbound(0) >= 1) // Invoke the synchronous call to the web // This thread is block until the method call returns // with the return value // NOTE: System.Convert.ToInt32 converts the string // argument to integer ReturnValue = objstockservice.getstockquote(args[0], 9

System.Convert.ToInt32(args[1])); // Display the results to the user Console.WriteLine("Stock quote for " + args[0] + " is " + ReturnValue); else // User did not enter the right number of parameters Console.WriteLine("You need to input 2 parameters. Try again."); SyncStockClient.exe is designed to be used at the command prompt. This application accepts two command-line parameters that will then be passed to the GetStockQuote method call of the StockService Web Service. Here's the line of code that invokes the Web Service method: ReturnValue = objstockservice.getstockquote(args[0], System.Convert.ToInt32(args[1])); When the application starts, the command-line is parsed by the GetCommandLineArgs method and the command-line entries are then stored in the args array. When the user starts the application correctly, args[0] will contain the StockSymbol parameter and args[1] will contain the DelayInSeconds parameter. Below is the output for SyncStockClient.exe: Since the Web Service call, in this example, is synchronous, the application has no choice but to wait for the processing to conclude 10

before running the next line of execution, which then prints the outcome of the method call. Let's now look at a similar application that calls StockService asynchronously. A Sample Asynchronous Method Call : This next example will also be a console-based application written in Visual Basic.NET. It's identical in functionality to SyncStockClient.exe with the exception that the GetStockQuote method will be invoked asynchronously. Here's the C# code for the console application, AsyncStockClient.exe, that uses the StockService Web Service: Listing2 AsyncStockClient Code using System; namespace AsyncStockClient /// <summary> /// Summary description for Class1. /// </summary> class AsyncStockClient /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) // // TODO: Add code to start application here // string ReturnValue; IAsyncResult AsyncResult; // Create the web service instance via the proxy class localhost.stockservice objstockservice = new localhost.stockservice(); if (args.getupperbound(0) >= 1) // Invoke the asynchronous call to the Web Service AsyncResult = objstockservice.begingetstockquote(args[0], System.Convert.ToInt32(args[1]), null, null); processing while loop // Method call returns right away // This thread is free to do more // Check for method completion in the 11

do more processing"); Console.Write("I'm not blocked. I can while (AsyncResult.IsCompleted == false) Console.Write("."); returned!"); Console.WriteLine("Method call has ReturnValue = objstockservice.endgetstockquote(asyncresult); Console.WriteLine("Stock quote for " + args[0] + " is " + ReturnValue); else Console.WriteLine("You need to input 2 parameters. Try again."); The call to BeginGetStockQuote starts the asynchronous communication process, sending out the method request and then returning immediately. The return value of this method call is not yet the actual stock quote, yet, as was the case in the synchronous version. Instead, it's an object of type IAsyncResult, which is part of the System.Runtime.Remoting.Messaging namespace. The AsyncResult object will be used later to poll for completion and to fetch the results of the method call: //Invoke the asynchronous call to the Web Service //NOTE: System.Convert.ToInt32 converts the string argument to integer AsyncResult = objstockservice.begingetstockquote(args[0], System.Convert.ToInt32(args[1]), null, null); The parameter list of the BeginGetStockQuote begins with the parameters of the synchronous method - StockSymbol and DelayInSeconds. The method has two additional parameters used in providing a callback mechanism for the asynchronous process. Since we won't be using a callback mechanism in this example, the C# code simply passes null to the last two parameters (we'll be covering the callback mechanism in a later example in this chapter). Once the Web Service method has been invoked asynchronously, the calling thread needs a way to find out when the operation has completed. The IAsyncResult class contains a property for just this purpose, called IsCompleted, which will return the Boolean value, 12

true, when the Web Service is finished processing the request. In the code, outlined below, we call the AsyncResult.IsCompleted method periodically to check for method call completion. //Method call returns right away! //This thread is free to do more processing //Check for method completion in the while loop Console.Write("I'm not blocked. I can do more processing"); while(asyncresult.iscompleted == false) Console.Write("."); To retrieve the results of the operation, we call the EndGetStockQuote method provided by the Web Service's proxy class: //Retrieve return value from the Web Service ReturnValue = objstockservice.endgetstockquote(asyncresult); The method accepts one parameter of type IAsyncResult. In this case, we pass the AsyncResult object that we originally received from the BeginGetStockQuote method. This is how the.net infrastructure is able to determine which result to give back to our code, since the client may have invoked any number of requests at the same time. Note that we need to wait for the AsyncResult.IsCompleted to return true before invoking the EndGetStockQuote method. If we call the EndGetStockQuote method before the operation is finished, it will block until the operation does in fact complete. In this example, the user starts the AsyncStockClient application, requesting the stock quote for Microsoft (MSFT) and setting a server-side delay of 5 seconds: 13

Since the Web Service call in this example, is asynchronous, the method call returns immediately and the calling thread is free to do more processing. In this case, the calling thread writes to the console to demonstrate that it's able to do more work: I'm not blocked. I can do more processing... At the same time, the client application is polling to check if the method call has returned. Upon completion of the call request, the client then prints the outcome of the method call: Method call has returned! Stock quote for msft is 67 Reference: Wrox Press, Professional ASP. NET Web Services: Asynchronous Programming, http://www.stardeveloper.com/articles/display.html?article=200112 1901&page=1 14