using asynchronous pages to perform asynchronous data binding

hi all,
I have a question about using asynchronous pages to perform asynchronous data binding. I searched google and found this sample code here http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
("Wicked Code: Asynchronous Pages in ...")

public partial class AsyncDataBind : System.Web.UI.Page
{
    private SqlConnection _connection;
    private SqlCommand _command;
    private SqlDataReader _reader;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Hook PreRenderComplete event for data binding
            this.PreRenderComplete +=
                new EventHandler(Page_PreRenderComplete);

            // Register async methods
            AddOnPreRenderCompleteAsync(
                new BeginEventHandler(BeginAsyncOperation),
                new EndEventHandler(EndAsyncOperation)
            );
        }
    }
    IAsyncResult BeginAsyncOperation (object sender, EventArgs e,
        AsyncCallback cb, object state)
    {
        string connect = WebConfigurationManager.ConnectionStrings
            ["PubsConnectionString"].ConnectionString;
        _connection = new SqlConnection(connect);
        _connection.Open();
        _command = new SqlCommand(
            "SELECT title_id, title, price FROM titles", _connection);
        return _command.BeginExecuteReader (cb, state);
    }

    void EndAsyncOperation(IAsyncResult ar)
    {
        _reader = _command.EndExecuteReader(ar);
    }

    protected void Page_PreRenderComplete(object sender, EventArgs e)
    {
        Output.DataSource = _reader;
        Output.DataBind();
    }

    public override void Dispose()
    {
        if (_connection != null) _connection.Close();
        base.Dispose();
    }
}

The code uses the BeginExecuteReader (cb, state) method to run an asynchronous command in the BeginAsyncOperation() method.
And EndExecuteReader(ar) method to sync the application and get a data reader in EndAsyncOperation() method.

Now my question: As I figured out, as long as you register Begin and End event handler in the page, any code that you place in them is treated in an asynchronous way.
if that is true, so why does the code uses an Asyncronous Command execution way in those handlers.
Dose it make any problem if we just execute the command in a synchronous way,
Or we have to execute our commands as Asynchronous when we want to execute them in an Asynchronous Page?

Use this code instead :

 IAsyncResult BeginAsyncOperation (object sender, EventArgs e,
        AsyncCallback cb, object state)
    {
        string connect = WebConfigurationManager.ConnectionStrings
            ["PubsConnectionString"].ConnectionString;
        _connection = new SqlConnection(connect);
        _connection.Open();
        _command = new SqlCommand(
            "SELECT title_id, title, price FROM titles", _connection);
        /Use ExecuteReader() instead of BeginExecuteReader(cb.state);
        return _command.ExecuteReader;
    }

 

0
ali_gili
1/27/2009 2:20:02 PM
asp.net.sql-datasource 29906 articles. 0 followers. Follow

0 Replies
549 Views

Similar Articles

[PageSpeed] 3

Reply:

Similar Artilces:

Converting a gridView using an Sql Datasource to a gridview who is not using an SQL DataSource
How can i rewrite this page so that i doesnt make use of an SqlDataSource?  <%@ Control Language="C#" AutoEventWireup="true" CodeFile="LoginHistory.ascx.cs" Inherits="Private_UserControls_WebUserControl" %> <html> <head> <%--<link rel="stylesheet" href="BaldwinPortal.css" mce_href="BaldwinPortal.css" type="text/css" />--%> <title>Login History</title> </head> <body style="margin:0 0 0 0;padding:0 0 0 0"> ...

How to: Asynchronously update the "client side data binding-tutorial" using declarative markup
Hello,I followed the tutorial on how to build "client side data binding" with Atlas as described in: http://atlas.asp.net/docs/Walkthroughs/GetStarted/databind.aspx Now, after having exactly the same webservice (see code at the end of this post) as described in the Tutorial, I would like to asynchronously update the page using a TimerControl but I just cannot make it work!What worked is:- using a button control and use the following declarative markup to  update the page - but unfortunately with a whole postback (i tried using update panel but without success):  ...

How to Data Transfer From Excel to Microsoft SQL Server Data base Using .Net.
Hai All, How to Data Transfer From Excel to Microsoft SQL Server Data base Using .Net. I have one Excel Sheet in that sheet 15 Fields (attributes) and 3000 records are there. In this 3000 records i want to store this (Excel) data into  5 related tables on Sql Server Database Using .Net.   How to store Excel Sheet data into Sql Server database. Please help me as soon as possible. Thank You Very Much...Have a Good Day... With RegardsSridhar...

how do i insert data into sql server using data from textboxes and sql connection and sql command
anyone can give me a simple explaination and code.. Thanx in advance Take a look @ Sample Code: How to add...Sushila Bowalekar PatelVisual ASP/ASP.NET MVPhttp://weblogs.asp.net/sushilasb There are a lot of tutorials out there, but I know they can be a bit confusing as they all approach things slightly differently. Basically a nice simple version would go like this:' *** First set up your connectionDim conConnection As New SqlConnection("server=servername;database=yourdatabase;uid=yourname;pwd=yourpassword;")' *** This line takes care of your sommand text and command connection in one ...

Using data bind server tags <%# ..%> without using Page.DataBind()
Hello, Does anybody know of a way to get databound server tags  (<%# ..%>) to work with out a call to Page.DataBind()? The reason I ask is that I have a problem that I have been looking into for over a day now and it looks like the culprit is a call to Page.DataBind(). Basically I have a user control that contains a datagrid and I need to have viewstate enabled in this grid so that I can get the checked state of checkboxes in the grid on a postback, essentially to delete the selected items. What I have found is that if I call Page.DataBind() from Page_Init(), the datagrid does n...

problem of Asynchronous Data Binding
code from http://msdn.microsoft.com/msdnmag/issues/05/10/WickedCode/default.aspx?loc=en when i run the AsyncDataBind.aspx example , nothing happen ,who can help me? thank you. my enviroment is : iis6.0 ,asp.net 2.0 , vs2005,sql 2005 dotnetstudy: code from http://msdn.microsoft.com/msdnmag/issues/05/10/WickedCode/default.aspx?loc=en when i run the AsyncDataBind.aspx example , nothing happen ,who can help me? thank you. my enviroment is : iis6.0 ,asp.net 2.0 , vs2005,sql 2005 Hi dotnetstudy, Since it is a double thread, please focus on another of your thread. http://forums.asp.n...

Asynchronous page over using Ajax ?
Can anyone explain to me if there is any advantage of using the Asynchronous page ("Async= true " ) over using Ajax with a synchronous page which spins out a separate server-side thread, and then uses Ajax to retrieve data after the response has returned.  Well, It depends.If you're using update panel you save nothing on the pag lifecycle and therefore your use of server threads stays the same as regular post back. In that case I'd recommend using an asynchronouspages (in case of pages heavy enough to justify that).However, using page methods or web methods with aj...

Binding the data to grid asynchronously
Hi All, Could any one tell me some good link which tells how to bind data to grid asynchronously?   Regards, Techwork. its a bit hard for .NET 1.1 for .NET 2.0, there is something already for you http://msdn.microsoft.com/msdnmag/issues/05/10/WickedCode/ look at asyn data bind section  James Wu (MIB426).NET is only way to goMCP, MCSE, MCDBA, MCSD, MCAD...

Binding using Sys.Preview.Data.DataSource, Sys.Preview.Binding and Sys.Preview.UI.TextBox
Hi all, I'm trying to figure out how to bind a webservice to a textbox using the DataSource, DataBinding and TextBox objects.this is my code: params = {    serviceURL:"WebServices/DemoWS.asmx",    loadMethod:"Sample",    parameters:{filter:"world"}};ds = $create(Sys.Preview.Data.DataSource,params);ds.load();var textbox = new Sys.Preview.UI.TextBox($get("txtdemo"));textbox.initialize();                   var binding = new Sys.Preview.Binding();binding.set...

Using Data Pager with SQL datasource
 Dear fellowsHow to use dataPager with SQL DataSource? this control is totally new for me? and Y we use data Pager, If we have GridView and DataList with Paging Facility?  Actually i want to make pages of a TABLE, 15 items per page... What should i use? Pager with ListView, GridView or DataList? thanks aliusmankhanC#.NET 3.5Web.DevAJAX aliusmankhan:How to use dataPager with SQL DataSource?To use the DataPager with a data control , the control must implmenet "IPageableItemContainer" interface.The ListView control Implements that interface and so you can use the Pag...

Using SQL data in Page Programming
I'm not sure what forum this really belongs in  Ok I have been working with ASP.NET the last 2 year and I know there is a better way to retrieve SQL date and to be used on my server side programming.  Basically, I have specific information stored in by SQL database (names, ID, ...). I would like to retrieve it and use the data in my Server side programming. IE: if my data point says X then want the Service side program (Page load) to do Y or Display Z. Currently, I create a Grid view (visibility = false) and pick off the information's by Gridview.Row(x).Cell(x).text. Th...

Load Page Asynchronously using ICallBackEventHandler
Hi,In my application, i try to load ascx file usingHttpContext.Current.Server.Execute I use Icallbackeventhandler to load page asynchronously but i get error.....Error executing child request for handler ‘System.Web.UI.Page’. When i make control read as normal html controls with runat="server"...it works for example <asp:textbox> i change it to <input type="text" runat="server"> -- this works, but for controls like CalendarExtender i have the problem Error executing child request , is there a workaround for this? kindly let me know My require...

implementing Asynchronous communication using .NET
Scenario: Step1: webclient will call a component to send xml document to another webserver2(some website), which on receiving XML,it send back an ack( all this is snycronous communication) and the component return control to webclient. Step2:(need to send the processed XML from webserver2 to webclient) webserver2 will send back processed xml to an HTTP handler. The HTTP handler should raise an event or some way notify the webclient to pull the xml and process ,so that the webclient can display results to the user any suggestions are appreciated. Thanks Web serv...

Trying to use the FAQ " Sorting and paging in the GridView control when not using data source controls "Sorting and paging in the GridView control when not using..."
and I am not getting the results I had hoped for.  I keep getting a "Compiler Error Message: CS0123: No overload for 'AdhocJobGridView_PageIndexChanged' matches delegate 'System.EventHandler'".   Here is my event handling... protected void AdhocJobGridView_PageIndexChanged(object sender, GridViewPageEventArgs e){ try { AdhocJobGridView.DataSource = wsBaseInfoArray; AdhocJobGridView.PageIndex = e.NewPageIndex; AdhocJobGridView.DataBind(); }catch (Exception ex) {throw ex; }   Here is my aspx... <asp:GridView ID="AdhocJobGridView...

Web resources about - using asynchronous pages to perform asynchronous data binding - asp.net.sql-datasource

Asynchronous Transfer Mode - Wikipedia, the free encyclopedia
and designed to unify telecommunication and computer networks . It was designed for a network that must handle both traditional high-throughput ...

Facebook adds asynchronous voice messages to Messenger app; begins testing VoIP in Canada
Facebook today released an update for its standalone Messenger app to allow users to record and send each other voice messages. The company also ...

Google Dart upgrade homes in on asynchronous programming
Google has released Dart 1.9, with a focus on asynchronous programming.

Decomposing Asynchronous Workers in Ruby
... pieces of our systems, we can potentially come away with new ways to compose the same functionality with multiple smaller pieces. Take asynchronous ...

AMD Dives Deep On Asynchronous Shading
... to reduce display chain latency, and finally features to reduce rendering latency. Key among the latter features set is support for asynchronous ...

Hero Academy brings smart, asynchronous strategy to Android
After a lengthy stay on iOS, Hero Academy is now available for Android. The turn-based strategy game uses a kind of card mechanic mixed with ...

Worms 2: Armageddon Finally Launches Asynchronous Multiplayer Mode
... crusades. The latest update to the sequel to the highly successful Worms finally adds what is understandably its most requested feature: asynchronous ...

Apple patents iPhone camera remote control with display, asynchronous notifications
The U.S. Patent and Trademark Office on Tuesday granted Apple a patent for a wireless accessory that can control an iPhone's camera functions, ...

Watch Dogs Asynchronous Multiplayer Trailer Turns This Into A Must-Buy Game
For the first time since I've laid eyes on Watch Dogs the game has finally portrayed itself as a must-buy title. All before now we've seen glimpses ...

Really Simple Asynchronous Web Services
Web services are better suited for the message-oriented communication paradigm, rather than remote procedure calls, the author says.

Resources last updated: 12/11/2015 4:12:55 PM