gpt4 book ai didi

c# - 调用调度程序和执行之间的时间真的很长

转载 作者:行者123 更新时间:2023-11-30 18:43:21 27 4
gpt4 key购买 nike

如果这是一个愚蠢的问题,我事先表示歉意。我的职业是嵌入式 C 程序员,C# 对我来说比较陌生。

我有一个应用程序,基本上可以归结为以下内容:一个线程轮询外部接口(interface)(profibus,以防有人感兴趣),当输入数据发生变化时,将引发一个事件并处理新数据。由于我需要更新的数据使用数据绑定(bind),因此我调用了调度程序。此设置可正常运行数百万次,但有时在执行委托(delegate)中的代码之前最多需要 6 秒。由于没有其他线程,我看不出有任何理由这样做。我使用以下事件处理程序。容器是对类数据绑定(bind)到的 TabItem 的引用。

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 */

}
);
}

轮询外部接口(interface)的线程基本上是这样的:

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);
}
}

我已经添加了打印以查看在调度程序“挂起”时该线程是否仍在运行。事实证明,事实并非如此。我不知道程序在调用和执行之间的几秒钟内在做什么,因为据我所知没有其他线程在运行。不幸的是,我没有 visual studio 2010 终极许可证,所以我不能使用 intellitrace 来回溯运行的内容。

非常感谢任何输入。

最佳答案

使用 thread.sleep 通常是不好的做法,您可能会卡住整个 UI 线程,从而无法正确调用 Dispatcher。我建议改用 DispatcherTimer

关于c# - 调用调度程序和执行之间的时间真的很长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4562577/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com