【问题标题】:C# Wait delegate finish before continueC#在继续之前等待委托完成
【发布时间】:2014-07-16 15:21:57
【问题描述】:

我需要从创建它的线程以外的线程访问 DataGridView 控件。我读到我必须使用委托并且它可以工作,但是我需要等待委托完成,然后再继续线程。我尝试在BeginInvoke 之后调用EndInvoke,但线程仍在继续。

public void ArrangeGrid()
{
    ArrangeGridHandler ag = ArrangeGridAsync;
    IAsyncResult result = ag.BeginInvoke(cb, null);
    ag.EndInvoke(result);
}

当我调用ArrangeGrid() 时,即使它没有完成,线程也会继续。我能怎么做? 谢谢!

【问题讨论】:

  • Delegate.BeginInvoke 不会在您的 gui 线程上调用它。试试Control/Form.Invoke(...);。这将在正确的线程上执行它并等待完成。

标签: c# multithreading asynchronous datagridview delegates


【解决方案1】:

当使用 Async 方法时,将为您创建一个新线程。

尝试使用Invoke

 public void ArrangeGrid()
    {          
         if(this.InvokeRequired) 
          { 
             Action  arrange = ArrangeGrid ;  
               this.Invoke(arrange); 
          }
          else
          {  
            //insert your code here  
          }
    }

【讨论】:

  • 它只有在我一步一步执行时才有效,否则线程似乎不等待ArrangeGrid完成。
  • 它有效,之前调用了另一种方法,它有同样的问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 2020-02-24
  • 1970-01-01
  • 2019-03-12
相关资源
最近更新 更多