代码之家  ›  专栏  ›  技术社区  ›  Ash Burlaczenko

C-如何逐行执行代码?

  •  0
  • Ash Burlaczenko  · 技术社区  · 15 年前

    以这个示例代码为例

    private void test()
    {
        Label1.Text = "Function 1 started.";
        function1(); //This function takes a while to execute say 15 seconds.
        Label2.Text = "Function 1 finished.";
    }
    

    如果运行此命令,您将无法看到函数1启动。所以我的问题是,是否有任何C函数可以调用“显示标签更改”。像这样的

    private void test()
    {
        Label1.Text = "Function 1 started.";
        this.DoProcess();       //Or something like this.
        function1();             
        Label2.Text = "Function 1 finished.";
    }
    

    我知道这可以用线程来完成,但是A想知道是否还有其他的方法。

    谢谢你。

    6 回复  |  直到 15 年前
        1
  •  6
  •   Yuriy Faktorovich    15 年前

    Application.DoEvents()

        2
  •  4
  •   egrunin    15 年前

    如果这是一个WinForms应用程序, Label1.Update() . 如果还不够的话:

    Label1.Update()
    Application.DoEvents()
    

    你通常都需要。

        3
  •  3
  •   Jordão    15 年前

    你的 function1 应该异步运行,以避免冻结UI。看看 BackgroundWorker 班级。

        4
  •  3
  •   Muhammad Hasan Khan    15 年前
    var context = TaskScheduler.FromCurrentSynchronizationContext(); // for UI thread marshalling
    Label1.Text = "Function 1 started.";
    Task.Factory.StartNew(() =>
    {
         function1();           
    }).ContinueWith(_=>Label2.Text = "Function 1 finished.", context);
    

    .NET 4任务并行库

        5
  •  1
  •   SqlRyan    15 年前

    由于UI线程正忙于运行代码,因此在更改标签的值后,它不会停止刷新表单,直到完成对代码的处理后,才会重新绘制表单本身。你可以用线程来完成,或者,正如其他人已经说过的,你可以使用 Application.DoEvents ,这将强制UI线程暂停执行并重新绘制表单。

        6
  •  0
  •   user195488    15 年前

    在哪里 private void test() 打电话?

    如果不在UI线程中,则可能需要 delegate :

    public delegate void UpdateLabelStatus(string status);
    
    ...
    
    private void test()
    {
    
         Invoke(new UpdateLabelStatus(LabelStatus1), status);
         ...
    
    }
    
    private void LabelStatus1(string status)
    {
    
         Label1.Text = status;
    }
    

    否则,你应该能够做到 Label1.Update(); 然后 Application.DoEvents();