Proxy > Gmail Facebook Yahoo!

Loading UserControl Dynamically in UpdatePanel



In this post, I will show you how to load different user control in UpdatePanel from different menu item click. I have found a lot of request in Asp.net Ajax Forum and some of them are having misconception about this. Once you complete reading this post you will be able to load controls dynamically and learn how to employ different helper controls like UpdateProgress, ModalPopupExtender while the UserControl is loading. First let us create plain page without the ajax support:
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PlainSampleMenu.aspx.cs" Inherits="PlainSampleMenuPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Plain Sample Menu</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
            <Items>
                <asp:MenuItem Text="File">
                    <asp:MenuItem Text="Load Control1"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control2"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control3"></asp:MenuItem>
                </asp:MenuItem>
            </Items>
        </asp:Menu>
        <br />
        <br />
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </form>
</body>
</html>
You are reading MyCodeLogic
Code Behind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PlainSampleMenuPage : System.Web.UI.Page
{
    private const string BASE_PATH = "~/DynamicControlLoading/";

    private string LastLoadedControl
    {
        get
        {
            return ViewState["LastLoaded"] as string;
        }
        set
        {
            ViewState["LastLoaded"] = value;
        }
    }

    private void LoadUserControl()
    {
        string controlPath = LastLoadedControl;

        if (!string.IsNullOrEmpty(controlPath))
        {
            PlaceHolder1.Controls.Clear();
            UserControl uc = (UserControl)LoadControl(controlPath);
            PlaceHolder1.Controls.Add(uc);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        LoadUserControl();
    }

    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        MenuItem menu = e.Item;

        string controlPath = string.Empty;

        switch (menu.Text)
        {
            case "Load Control2":
                controlPath = BASE_PATH + "SampleControl2.ascx";
                break;
            case "Load Control3":
                controlPath = BASE_PATH + "SampleControl3.ascx";
                break;
            default:
                controlPath = BASE_PATH + "SampleControl1.ascx";
                break;
        }

        LastLoadedControl = controlPath;
        LoadUserControl();
    }
}
As you can see we are loading the UserControls in the PlaceHolder Control on different menu item click. If you are wondering why I am also loading the controls in Page Load event based upon the ViewState, the reason is otherwise those dynamically loaded controls will not be visible in the consequent postbacks. There are few good articles written by Scott Mitchell on dynamically loading Controls which you will find in the following links:
You are reading MyCodeLogic
Now let us ajaxify this page, lets wrap the PlaceHolder with an UpdatePanel control. The following shows the markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Sample Menu</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
            <Items>
                <asp:MenuItem Text="File">
                    <asp:MenuItem Text="Load Control1"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control2"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control3"></asp:MenuItem>
                </asp:MenuItem>
            </Items>
        </asp:Menu>
        <br />
        <br />
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Menu1" />
            </Triggers>
        </asp:UpdatePanel>
    </form>
</body>
</html>
Since the Menu control resides outside the UpdatePanel we will also need a AsyncPostBackTrigger for the Menu Control. Now run this page, you will find the controls are loaded without a full postback.
Now let us further enhance this page with UpdateProgress and AjaxControlToolKit's ModalPopupExtender. First with the UpdateProgress Control.
You are reading MyCodeLogic
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Sample Menu - UpdateProgress</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
            <Items>
                <asp:MenuItem Text="File">
                    <asp:MenuItem Text="Load Control1"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control2"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control3"></asp:MenuItem>
                </asp:MenuItem>
            </Items>
        </asp:Menu>
        <br />
        <br />
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
                    <ProgressTemplate>
                        Loading....
                    </ProgressTemplate>
                </asp:UpdateProgress>
                <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Menu1" />
            </Triggers>
        </asp:UpdatePanel>
    </form>
</body>
</html>
As you can see we have added a UpdateProgress Control in the UpdatePanel ContentTemplate. But the UpdateProgress does not get visible when you click any of the menu item. This is the true nature of UpdatePanel, it does not shows the UpdateProgress if the control is out side the UpdatePanel which caused the postback. We have to manually show the UpdateProgress by the JavaScript code like the following:
You are reading MyCodeLogic
 
<script type="text/javascript">

    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_initializeRequest(initializeRequest);
    prm.add_endRequest(endRequest);

    var _postBackElement;

    function initializeRequest(sender, e)
    {
        if (prm.get_isInAsyncPostBack())
        {
            e.set_cancel(true);
        }

        _postBackElement = e.get_postBackElement();

        if (_postBackElement.id.indexOf('Menu1') > -1)
        {
            $get('UpdateProgress1').style.display = 'block';
        }
    }

    function endRequest(sender, e)
    {
        if (_postBackElement.id.indexOf('Menu1') > -1)
        {
            $get('UpdateProgress1').style.display = 'none';
        }
    }
</script>
Now run the page, you will find the UpdateProgress Control is showing the loading message no matter which control caused the postback.
In this final section we will implement the AjaxControlToolKit's ModalPopupExtender to show the loading message, this will give you a similar look of CodePlex Site. The following shows the source:
You are reading MyCodeLogic
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu2.aspx.cs" Inherits="SampleMenuPage2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Sample Menu - ModalPopupExtender</title>
    <style type="text/css">
        .modalBackground
        {
            background-color:#dcdcdc;
            filter:alpha(opacity=60);
            opacity:0.60;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
            <Items>
                <asp:MenuItem Text="File">
                    <asp:MenuItem Text="Load Control1"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control2"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control3"></asp:MenuItem>
                </asp:MenuItem>
            </Items>
        </asp:Menu>
        <br />
        <br />
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Menu1" />
            </Triggers>
        </asp:UpdatePanel>
        <asp:Panel ID="Panel1" runat="server" style="background-color:#ffffff;display:none;width:400px">
            <div style="padding:8px">
                <h2>Loading...</h2>
            </div>
        </asp:Panel>
        <ajaxToolKit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="Panel1" PopupControlID="Panel1" BackgroundCssClass="modalBackground" DropShadow="true" />
        <script type="text/javascript">

            var prm = Sys.WebForms.PageRequestManager.getInstance();

            prm.add_initializeRequest(initializeRequest);
            prm.add_endRequest(endRequest);

            var _postBackElement;

            function initializeRequest(sender, e)
            {
                if (prm.get_isInAsyncPostBack())
                {
                    e.set_cancel(true);
                }

                _postBackElement = e.get_postBackElement();

                if (_postBackElement.id.indexOf('Menu1') > -1)
                {
                    $find('ModalPopupExtender1').show();
                }
            }

            function endRequest(sender, e)
            {
                if (_postBackElement.id.indexOf('Menu1') > -1)
                {
                    $find('ModalPopupExtender1').hide();
                }
            }
        </script>
    </form>
</body>
</html> 
You are reading MyCodeLogic
As you can see we first created a custom style which will be shown as the background style when the modal popup is visible, next we have added a regular Asp.net Panel control which will be shown as the modal popup. We have initially set the Panel control display mode to none, so there will be no flicker when the modal popup is shown. At last, we have added a ModalPopupExtender and sets its required property. The previous rule also applies here, we have to manually show/hide the ModalPopup which we are doing in the above JavaScript code. You will also found few cool techniques of ModalPopupExtender in this link.
To run the sample first create a AjaxControlToolKit enable site website then create a folder DynamicControlLoading folder and copy the files in the following attachment.
[Read More...]


Secure Cookie



This my second post of almost same topic asp.net lacking. This time it is Cookie. Still Asp.net has the lacking of creating encrypted cookie. Here is another handy class which generates encrypted cookie.
Usage:
//Writing CookieSecureCookie.Set(Response, "Key1", "Value1", DateTime.Now.AddDays(1));
SecureCookie.Set(Response, "Key1", "Value1"); //Overloaded 
//Reading Cookiestring key1Value = SecureCookie.Get(Request, "Key1");
SecureCookie:
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Diagnostics;
using System.Security.Cryptography;


public sealed class SecureCookie{
    //Rijndael Key size is 256 bit or 32 byte, Can also be mentioned in web.config instead of hardcoding    private static readonly byte[] Key = new byte[] {45, 236, 171, 7, 85, 6, 41, 34, 216, 14, 78, 156, 78, 3, 103, 154, 9, 150, 65, 54, 226, 95, 68, 79, 159, 36, 246, 57, 177, 107, 116, 8};

    [DebuggerStepThrough()]
    public static void Set(HttpResponse response,
    string key,
    string value,
    DateTime expire)
    {
        HttpCookie cookie = new HttpCookie(HttpUtility.UrlEncode(Encrypt(key)), HttpUtility.UrlEncode(Encrypt(value)));

        if ((expire != DateTime.MinValue) && (expire != DateTime.MaxValue))
        {
            cookie.Expires = expire;
        }

        response.Cookies.Set(cookie);
    }

    [DebuggerStepThrough()]
    public static void Set(HttpResponse response,
    string key,
    string value)
    {
        Set(response, key, value, DateTime.MaxValue);
    }

    [DebuggerStepThrough()]
    public static string Get(HttpRequest request, string key)
    {
        HttpCookie cookie = request.Cookies[HttpUtility.UrlEncode(Encrypt(key))];

        if (cookie == null)
        {
            return null;
        }

        if ((cookie.Value == null) || (cookie.Value.Length == 0))
        {
            return null;
        }

        string value = HttpUtility.UrlDecode(cookie.Value);

        return Decrypt(value);
    }

    [DebuggerStepThrough()]
    private static string Encrypt(string plain)
    {
        if ((plain == null) || (plain.Length == 0))
        {
            return null;
        }

        using(SymmetricAlgorithm crypto = CreateCrypto())
        {
            return System.Convert.ToBase64String(Read(crypto.CreateEncryptor(), Encoding.ASCII.GetBytes(plain)));
        }
    }

    [DebuggerStepThrough()]
    private static string Decrypt(string cipher)
    {
        if ((cipher == null) || (cipher.Length == 0))
        {
            return null;
        }

        using(SymmetricAlgorithm crypto = CreateCrypto())
        {
            return Encoding.ASCII.GetString(Read(crypto.CreateDecryptor(), System.Convert.FromBase64String(cipher)));
        }
    }

    [DebuggerStepThrough()]
    private static SymmetricAlgorithm CreateCrypto()
    {
        //Using Rijndael as it is much more secure among the others        SymmetricAlgorithm crypto = new RijndaelManaged();

        crypto.Key = Key;
        crypto.IV = new byte[crypto.IV.Length];

        return crypto;
    }

    [DebuggerStepThrough()]
    private static byte[] Read(ICryptoTransform transformer,
    byte[] data)
    {
        using(MemoryStream ms = new MemoryStream())
        {
            using(CryptoStream cs = new CryptoStream(ms, transformer, CryptoStreamMode.Write))
            {
                cs.Write(data, 0, data.Length);
                cs.FlushFinalBlock();

                return  ms.ToArray();
            }
        }
    }
}
[Read More...]


Showing Modal Progress Dialog in all Ajax Operation



Modal Progress Dialog
If you ever like to show a Modal Progress dialog like the above for any ajax operation no matter which Update Panel or Web Service call is responsible for it, the following code will do the same.
You are reading MyCodeLogic
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    [System.Web.Services.WebMethod()]
    public static string GetDate()
    {
        //Doing a fake delay for 3 seconds
        System.Threading.Thread.Sleep(3000);

        return DateTime.Now.ToString();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lblDate1.Text = lblDate2.Text = DateTime.Now.ToString();
        }
    }

    protected void btnDate1_Click(object sender, EventArgs e)
    {
        //Doing a fake delay for 3 seconds
        System.Threading.Thread.Sleep(3000);
        lblDate1.Text = DateTime.Now.ToString();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Modal Dialog Progress</title>
    <style type="text/css">
        .modalBackground
        {
            background-color:#e6e6e6;
            filter:alpha(opacity=60);
            opacity:0.60;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset>
            <legend>UpdatePanel</legend>
            <div>
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>
                        <asp:Label ID="lblDate1" runat="server"></asp:Label>
                        <asp:Button ID="btnDate1" runat="server" Text="Get Date" OnClick="btnDate1_Click" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </fieldset>
        <fieldset>
            <legend>PageMethods</legend>
            <div>
                <asp:Label ID="lblDate2" runat="server"></asp:Label>
                <asp:Button ID="btnDate2" runat="server" Text="Get Date" OnClientClick="return btnDate2_Click()" />
            </div>
        </fieldset>
        <asp:Panel ID="pnlProgress" runat="server" style="background-color:#ffffff;display:none;width:400px">
            <div style="padding:8px">
                <table border="0" cellpadding="2" cellspacing="0" style="width:100%">
                    <tbody>
                        <tr>
                            <td style="width:50%"></td>
                            <td style="text-align:right">
                                <img alt="" src="indicator-big.gif" />
                            </td>
                            <td style="text-align:left;white-space:nowrap">
                                <span style="font-size:larger">Loading, Please wait ...</span>
                            </td>
                            <td style="width:50%"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </asp:Panel>
        <ajaxToolKit:ModalPopupExtender ID="mpeProgress" runat="server" TargetControlID="pnlProgress" PopupControlID="pnlProgress" BackgroundCssClass="modalBackground" DropShadow="true" />
    </form>
    <script type="text/javascript">

        Sys.Net.WebRequestManager.add_invokingRequest(onInvoke);
        Sys.Net.WebRequestManager.add_completedRequest(onComplete);

        function onInvoke(sender, args)
        {
            $find('<%= mpeProgress.ClientID %>').show();
        }

        function onComplete(sender, args)
        {
            $find('<%= mpeProgress.ClientID %>').hide();
        }

        function btnDate2_Click()
        {
            PageMethods.GetDate (
                                    function(result)
                                    {
                                        var lbl = $get('<%= lblDate2.ClientID %>');

                                        if (document.all)
                                        {
                                            lbl.innerText = result;
                                        }
                                        else
                                        {
                                            lbl.textContent = result;
                                        }
                                    }
                                );

            return false;
        }

        function pageUnload()
        {
            Sys.Net.WebRequestManager.remove_invokingRequest(onInvoke);
            Sys.Net.WebRequestManager.remove_completedRequest(onComplete);
        }

    </script>
</body>
</html>
You are reading MyCodeLogic 
The main trick is hooking the two special events of Sys.Net.WebRequestManager class. This class is responsible for managing all kinds of communication with the server, even a manual invoke of a Sys.Net.WebRequest class will bring this class into action. It fires the invokingRequest before making an Ajax call and fires the completeRequest once the method completes. We are simply showing/hiding the modal popup extender in these events.
[Read More...]


Utilize ThreadPool in WebService



The following code snippet will show you how to create a multi-threaded web service. For the sake of the example, let us assume that we are creating Video Search Service, which will search different sites such as YouTube, MetaCafe, and DailyMotion for a given keyword and returns a composite result. Since this search can be done independently, we can surly invoke separate threads for each search. Let us see how we can utilize the built-in ThreadPool to create a multithread web service.
    1 using System;
    2 using System.Threading;
    3 using System.Collections;
    4 using System.Collections.Generic;
    5 using System.Web;
    6 using System.Web.Services;
    7 
    8 
    9 public class Video
   10 {
   11     public string Title;
   12     public string Author;
   13     public string Description;
   14     public string Url;
   15     public string OriginalUrl;
   16     public string Thumbnail;
   17     public string Source;
   18 }
   19 
   20 [WebService(Namespace = "http://tempuri.org/")]
   21 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   22 public class VideoSearchService : WebService
   23 {
   24     public VideoSearchService()
   25     {
   26     }
   27 
   28     [WebMethod()]
   29     public List<Video> Search(string keyword)
   30     {
   36         List<Video> result = new List<Video>();
   37         List<ManualResetEvent> locks = locks = new List<ManualResetEvent>();
   38         ManualResetEvent evt;
   39 
   40         evt = new ManualResetEvent(false);
   41         locks.Add(evt);
   42         ThreadPool.QueueUserWorkItem(new WaitCallback(SearchDailyMotion), (object)(new object[] { keyword, result, evt}));
   43 
   44         evt = new ManualResetEvent(false);
   45         locks.Add(evt);
   46         ThreadPool.QueueUserWorkItem(new WaitCallback(SearchMetaCafe), (object)(new object[] { keyword, result, evt }));
   47 
   48         evt = new ManualResetEvent(false);
   49         locks.Add(evt);
   50         ThreadPool.QueueUserWorkItem(new WaitCallback(SearchYouTube), (object)(new object[] { keyword, result, evt }));
   51 
   52         //This will ensure that all the threads completes its search
   53         EventWaitHandle.WaitAll(locks.ToArray());
   54 
   55         return result;
   56     }
   57 
   58     private void SearchDailyMotion(object state)
   59     {
   60         object[] triplet = (object[])state;
   61 
   62         string keyword = (string)triplet[0];
   63         List<Video> result = (List<Video>)triplet[1];
   64         ManualResetEvent evt = (ManualResetEvent)triplet[2];
   65 
   66 
   67         //DailyMotion will searhed over here
   68 
   69         evt.Set(); // Search is complete, so notify the parent thread
   70     }
   71 
   72     private void SearchMetaCafe(object state)
   73     {
   74         object[] triplet = (object[])state;
   75         string keyword = (string)triplet[0];
   76         List<Video> result = (List<Video>)triplet[1];
   77         ManualResetEvent evt = (ManualResetEvent)triplet[2];
   78 
   79         //MetaCafe will be searched over here
   80 
   81         evt.Set(); // Search is complete, so notify the parent thread
   82     }
   83 
   84     private void SearchYouTube(object state)
   85     {
   86         object[] triplet = (object[])state;
   87         string keyword = (string)triplet[0];
   88         List<Video> result = (List<Video>)triplet[1];
   89         ManualResetEvent evt = (ManualResetEvent)triplet[2];
   90 
   91         // YouTube will be searched over here
   92 
   93         evt.Set(); // Search is complete, so notify the parent thread
   94     }
   95 }

The whole thing has been done in four steps:
 Step 1:
 We created few variables:
  • A Generic List of Video which holds the search result
  • A Generic List of Locks which is actually ManualResetEvent class
  • A ManualResetEvent class to instantiate for different search.
Step 2:
Starting each Search, this steps are repeated for the 3 different search:
  • We created an Instance ManualResetEvent class and Adds it in the locks list. ManualResetEvent is special class, which allows us to communicate with different threads by signaling.
  • Next, we queue a Task in a ThreadPool passing the Keyword, The Result list where the search result will be appended by the child thread and ManualResetEvent. The ThreadPool class method QueueUserWorkItem only takes a WaitCallback delegate which only accepts a single argument of object type and that's way we creating array on the fly and putting these items in that array. When a task is queued in the ThreadPool, the ThreadPool picks a free thread from its pool fires the thread to run the assigned method in that thread.
Step 3:
Inside the Child Thread :
  • Cast back the argument to proper types.
  • Search the Site. I have commnted this to make the code shorter
  • Then call the set() method of the ManualResetEvent. By calling this method, we are sending signal to the parent thread that the thread has done its job.
Step 4:
The parent thread:
  • The Parent threads call the EventWaitHandle.WaitAll(). This ensures that the parent thread will wait until all the child threads complete its job.
And We are Done!
Few Notes:
  • It is not possible to access the HttpContext.Current from the Child Thread method which means it also not possible to access the Request, Response, Cache, Session etc. If you need any of these objects in the child thread method then you also have to pass it in the WaitCallback like we did in the above.
  • Never Creates a New Thread alternatively use the Built in ThreadPool class.
  • Queuing a Task does not ensure that it will started be instantly, it completely depends upon the current usage of the ThreadPool, if the ThreadPool is already saturated with previous tasks then there might be a chance that your application will perform poorly even comparing with the Single threaded approach.
[Read More...]



Send mail to your Friends.  

Expert Feed

 
Return to top of page Copyright © 2011 | My Code Logic Designed by Suneel Kumar