Wednesday, October 13, 2010

How to implement a background worker thread

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        int? time;
        public int Time
        {
            get
            {
                if (this.time.HasValue) return time.Value;
                return (time = (int)(Session["time"] ?? 0)).Value;
            }
            set
            {
                Session["time"] = this.time = value;
            }
        }
        public System.Threading.Thread Current
        {
            get { return (System.Threading.Thread)Session["Current"]; }
            set { Session["Current"] = value; }
        }
        public void Start(object sender, EventArgs e)
        {
            this.Time = 0;
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(Process));
            this.Current = thread;
            thread.Start();
        }
        private void Process()
        {
            this.Time++;
            ///
            /// some operation on each second. 
            ///
            System.Threading.Thread.Sleep(1000);
            Process();
 
        }
        protected void Update(object sender, EventArgs e)
        {
            this.lblTime.Text = this.Time.ToString();
        }
        protected void Stop(object sender, EventArgs e)
        {
            if (this.Current != null)
            {
                this.Current.Abort();
                while (this.Current.IsAlive) System.Threading.Thread.Sleep(1);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button runat="server" ID="btnStart" Text="Start" OnClick="Start" />
        <asp:Button runat="server" ID="btnUpdate" Text="Update Time" OnClick="Update" />
        <asp:Button runat="server" ID="btnStop" Text="Stop" OnClick="Stop" />
        <hr />
        <asp:Label runat="server" ID="lblTime" />
    </form>
</body>
</html>

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...