简体   繁体   中英

Mulitthreading problem with BeginInvoke, EndInvoke?

I have a client application, that displays realtime values. The values are provided through a DDE-Advise. These realtime values are moving axis of a cnc-machine. So there are about 100 advises per minute comming in through this DdeClientAdvise -Method.
When the application is getting many DDE-Advises it seems that suddenly all adivses are lost.
I reduced the problem to the following:

public class NcddeZugriff
{
  private DdeClient _ddeClient; //see http://ndde.codeplex.com/

  public NcDdeZugriff()
  {
    _ddeClient = new DdeClient("ncdde", "machineswitch");
    _ddeClient.Connect();
    _ddeClient.Advise += DdeClientAdvise;
  }

  private delegate void CallbackDelegate(object sender, DdeAdviseEventArgs e);    

  private void DdeClientAdvise(object sender, DdeAdviseEventArgs e)
  {
    CallbackDelegate callbackDelegate = DdeClientAdviseCallback;
    _logging.InfoFormat("Advise-Callback for {0}", e.Item);
    //LINE A : return;

    callbackDelegate.BeginInvoke(sender, e, callbackDelegate.EndInvoke, null);
  }

  private void DdeClientAdviseCallback(object sender, DdeAdviseEventArgs e)
  {
    _logging.InfoFormat("Asynchron for {0}", e.Item);
    //do some work with e.Text...
  }
}

If I remove comment LINE A, everything works fine, no advise got lost. All the advises are being logged.
If I enable the BeginInvoke, after awhile the DdeClientAdvise -Method is not being called anymore, no more log-entries.

What am I doing wrong with BeginInvoke, EndInvoke?

Edit: Add some more Information about the class.

don't you have to call EndInvoke inside DdeClientAdviseCallback?

It seems like @Hans Passant was right: the delegate was getting garbage collected. Storing the delegate in a field seems to solve the issue.
Although I changed the design of the whole project. So I can't say for sure, that this solved the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM