开发者

Timer control not working in ASP.net

I have a situation like this.

  1. TestClass - a class defined in UI Layer
  2. test - a class level variable
  3. Submit button calls a function DoSomeThing()..It performs some operation in Busines Layer keeps on updating the Status Property of the class
  4. Timercontrol getting the status (from same variable test)to display in UI

Submit button runs by a thread (say thread 1 ) and starts the operation. Is is this thread which updates the status property from the BL

Timer control creates a new thread each time to run the TimerEvent (Say thread 2 , 3 etc).

Issue here is that test.Status property , which is updated by thread1 is not accessible by other thread.. It is always null , even though the property has been updated by thread 1..

What is the solution for this ? Thanks in advance

public class TestClass                   //---->#1
{   
    private test = new Test() ;       //---->#2          

    protected void SubmitButon_Click(object sender, EventArgs e)
    {             
      //  This is performed by Thread1
      test.DoSomeThing()             //------>#3
    }   

    protected void UpdateTimer_Tick(object sender, EventArgs e)
    {
      // Timer controls sends out开发者_运维技巧 a new thread each time
      Label1.Text =  test.Status;           //------>#4
    }   
}


here's sample to use delegate and update UI ements from different thread

    delegate string CallFunctionDelegate(string arg1, string arg2);

    private void btnStart_Click(object sender, EventArgs e)
    {
        CallFunctionDelegate delegRunApps = new CallFunctionDelegate(DoSomeThingBig);

        AsyncCallback CallBackAfterAsynOperation = new AsyncCallback(AfterDoingSomethingBig);

        delegRunApps.BeginInvoke("", "", CallBackAfterAsynOperation, null);
    }

    private string DoSomeThingBig(string arg1, string arg2)
    {
        #region Implemetation of time consuming function
        //Implemetation of time consuming function

        for (int i = 0; i < 5; i++)
        {
            Thread.Sleep(1000);

            if (btnStart.InvokeRequired)
            {
                btnStart.Invoke((new MethodInvoker(delegate { btnStart.Text = i.ToString(); })));
            }
            else
            {
                btnStart.Text = i.ToString();
            }
        } 
        #endregion

        return arg1.Replace("freetime", arg2);
    }

    private void AfterDoingSomethingBig(IAsyncResult result)
    {
        MessageBox.Show("Finaly Done!! ;) ");

        btnStart.Invoke((new MethodInvoker(delegate { btnStart.Text = "Start"; })));
    }


Issue happens because a new instance is created by the timerthread eachtime after as Line #2 is executed..Hence test.Status is always null.. That was the reason for the issue

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜