使用GTKSharp时触发System.AccessViolationException问题求助
Windows下GTKSharp应用运行10分钟后触发内存访问异常的问题
我开发了一款与设备通信的应用,设备数据刷新率为1秒。为实现可移植性,采用GTKSharp构建GUI(首次使用GTK,基于Glade 3.40模板开发,未做自定义实现)。应用可正常运行,但仅在Windows系统运行约10分钟后会抛出以下异常,Linux仅测试启动暂未发现问题:
Fatal error. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at Gtk.Image.set_IconName(System.String) ...
核心简化代码
class MainWindow { private readonly System.Threading.Timer refreshTimer; [UI] private Image? firstIndicator = null; // 其他30个Image控件 public MainWindow() : this(new Builder("MainWindow.glade")) { } private MainWindow(Builder builder) : base(builder.GetRawOwnedObject("MainWindow")) { builder.Autoconnect(this); refreshTimer = new Timer(refreshTimer_Elapsed); refreshTimer.Change(500, 1000); } private void refreshTimer_Elapsed(object state) { UpdateValues(); } private bool UpdateValues() { MyDataType data = device.ReadData(); // 当前为同步读取,异步改造中 UiChangeIndicatorState(firstIndicator, data?.firstBoolData); // 其他30个指示器的更新逻辑 } private void uiChangeIndicatorState(Image target, bool? state) { const string indFalse = "dialog-error"; const string indTrue = "dialog-information"; const string indDisconnected = "dialog-question"; if (state.HasValue) target.IconName = state.Value ? indTrue : indFalse; else target.IconName = indDisconnected; } }
已尝试的解决方案(均未解决)
- 使用
Threads.AddIdle(0, UpdateValues)确保GUI线程更新UI; - 将设备读取改为异步并结合
Threads.AddIdle; - 为
MyDataType加锁,但导致刷新率降至5秒一次; - 调整定时器周期,异常触发时间与周期呈指数相关,但需保持1秒刷新率;
- 替换Image为Label控件,仍触发同类异常(异常位置变为
at Gtk.Label.set_Text(System.String))。
当前使用NuGet包GtkSharp 3.24.24.95和.NET 7,怀疑是底层C++库问题。请问问题源于代码还是库?若为库问题,降级是否有效?应选择哪个版本?
内容的提问来源于stack exchange,提问作者Jirka Picek
相关产品推荐
相关产品推荐

