如何在处理记录

时间:2015-05-11 17:42:12

标签: c# asynchronous delegates

我有一个用c#编写的.net网络应用程序。从前端开始,我点击一个启动漫长过程的按钮。循环逻辑出现在较低层。每次循环时,我都会使用一个委托将它传递给下一层,它会做同样的事情。使用委托将消息传递给UI。如果我单步执行此操作,它似乎可以正常工作,但页面实际上并未更新,直到最后。我把需要更新的文字放在更新面板中。我错过了什么。

public delegate void ProcessedEventHandler(object sender, string msg);
public delegate void LongTimeTaskDelegate();

public class FileApplicationFrameWork
{
    static List<Application> lstApplications = new List<Application>();
    public event ProcessedEventHandler OnRecordProcessed;

    //Constructor
    public FileApplicationFrameWork()
    {
        //Get test data
        TestDataMgt oTestMgt = new TestDataMgt();
        lstApplications = oTestMgt.GetApplicants();
    }

    public void FileApplicationWithoutRegistering()
    {
        try
        {
            int i = 0;

            foreach (Application oApplication in lstApplications)
            {
                if (i < 5)
                {               
                    DoTheWork(oApplication); //This is the long process                
                    OnRecordProcessed(this, "Record Number"); 
                    i++;
                }
            }
        }
        catch (Exception)
        {

        }
    }

    public void DoTheWork(Application oApplication)
    {
        System.Threading.Thread.Sleep(10000);
    }
}

然后上升到中间层...

 public delegate void DisplayMessageEventHandler(object sender, string msg);

    public class FileApplicationTests
    {

       public event DisplayMessageEventHandler OnReadyToBeDisplayed;

        public string FileApplication()
        {
            string msg = string.Empty;

            try
            {
                FileApplicationFrameWork filer = new FileApplicationFrameWork();
                filer.OnRecordProcessed += new ProcessedEventHandler(PrintMsg);
                filer.FileApplicationWithoutRegistering();
             }
            catch (Exception ex)
            {
                msg = "Failed." + " " + DateTime.Now.ToString() + " " + ex.Message;
            }
            finally
            {
                //browser.Close();
            }

            return msg;
        }

        private void PrintMsg(object sender, string msg)
        {
            OnReadyToBeDisplayed(this, msg);
        }
    }
}

最后是UI ......

单击按钮,此代码将运行...

FileApplicationTests fileApplicationPageTest = new FileApplicationTests();   
fileApplicationPageTest.OnReadyToBeDisplayed += new DisplayMessageEventHandler(WriteToLog);
fileApplicationPageTest.FileApplication(); 

此函数应更新文字:

private void WriteToLog(object sender, string log_entry)
    {      
            Literal1.Text += log_entry + "<br/>";
            UpdatePanel1.Update();
    }

0 个答案:

没有答案