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.
public class NcddeZugriff
{
private DdeClient _ddeClient; //see http://ndde.codeplex.com/
public NcDdeZugriff()
{
_ddeClient = new DdeClient("ncdde", "machineswitch");
_ddeClient.Connect();开发者_JAVA百科
_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 theDdeClientAdvise
-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.
精彩评论