How do I wait for a C# event to be raised?

前端 未结 5 1742
再見小時候
再見小時候 2021-01-01 23:38

I have a Sender class that sends a Message on a IChannel:

public class MessageEventArgs : EventArgs {
  public Message         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 00:04

    Have you tried assigning the function to call asynchronously to a delegate, then invoking the mydelegateinstance.BeginInvoke?

    Linky for reference.

    With the below example, just call

    FillDataSet(ref table, ref dataset);
    

    and it'll work as if by magic. :)

    #region DataSet manipulation
    ///Fills a the distance table of a dataset
    private void FillDataSet(ref DistanceDataTableAdapter taD, ref MyDataSet ds) {
      using (var myMRE = new ManualResetEventSlim(false)) {
        ds.EnforceConstraints = false;
        ds.Distance.BeginLoadData();
        Func distanceFill = taD.Fill;
        distanceFill.BeginInvoke(ds.Distance, FillCallback, new object[] { distanceFill, myMRE });
        WaitHandle.WaitAll(new []{ myMRE.WaitHandle });
        ds.Distance.EndLoadData();
        ds.EnforceConstraints = true;
      }
    }
    /// 
    /// Callback used when filling a table asynchronously.
    /// 
    /// Represents the status of the asynchronous operation.
    private void FillCallback(IAsyncResult result) where MyDataTable: DataTable {
      var state = result.AsyncState as object[];
      Debug.Assert((state != null) && (state.Length == 2), "State variable is either null or an invalid number of parameters were passed.");
    
      var fillFunc = state[0] as Func;
      var mre = state[1] as ManualResetEventSlim;
      Debug.Assert((mre != null) && (fillFunc != null));
      int rowsAffected = fillFunc.EndInvoke(result);
      Debug.WriteLine(" Rows: " + rowsAffected.ToString());
      mre.Set();
    }
    

提交回复
热议问题