realy long time between invoking dispatcher and execution
I apologize beforehand if this is a stupid question. I am an embedded C programmer by profession and C# is relatively new to me.
I have an application which basically boils down to the following: One thread which polls an external interface (profibus in case anyone is interested), when the input data changes an event is raised and the new data is handled. Since the data I need to update uses databinding I invoke the dispatcher. This setup works properly millions of times, but sometimes it takes up to 6 seconds before the code in the delegate is executed. Since there are no other threads, I can not see any reason for this. I use the following event handler. Container is a reference to the TabItem to which the class is databound.
public void newSlave_InputChanged(object sender, InputChangedEventArgs e)
{
DateTime beforeDisp = DateTime.Now;
Container.Dispatcher.Invoke(DispatcherPriority.Send, (Action)delegate()
{
DateTime afterDisp = DateTime.Now;
if (afterDisp.Subtract(beforeDisp).TotalSeconds > 1)
{
/* Breakpoint here to detect the problem */
}
/* Do the work I need to do */
}
);
}
The thread polling the external interface ba开发者_开发知识库sically look something like this:
void monitorSlaves()
{
while (true)
{
if (cardOnline)
{
foreach (slave slv in slaves)
{
/* get the data */
if (dataChanged)
{
/* raise event */
}
}
}
Console.WriteLine(string.Format("{0}: Monitor slaves", DateTime.Now));
}
Thread.Sleep(200);
}
}
I have added the print to see if this thread is still running while the dispatcher "hangs". As it turns out, it does not. I have no idea what the program is doing in the seconds in between the invocation and the execution, since there are no other threads running as far as I know. Unfortunately I do not have a visual studio 2010 ultimate license, so I cannot use intellitrace to backtrace what ran.
Any input is greatly appreciated.
using thread.sleep is generally bad practice, you might be freezing the entire UI thread so that the Dispatcher is not being called properly. I recommend using a DispatcherTimer instead
Are you sure that you're seeing the input when you think you are?
One possible problem is that the interface card DLL is not reporting the input to you in a timely manner.
Another possible problem is that the UI thread is too busy to run your delegate. However, 6 seconds is a long time to be unresponsive.
You can add simple tracing to determine the cause. Just call Trace.TraceInformation
to log simple strings in Release mode. Then download DebugView
, which can display those trace messages. You can also set up DebugView to timestamp them and save them to a file.
P.S. Coincidentally, I'm a .NET developer who is now working on embedded firmware. :)
I bet the delay because of garbage collector is gathering bunch of small objects which you created. run perfmon and watch all the collection.
精彩评论