问题描述
我正在使用后台线程通过USB初始化仪器.当我尝试打开设备时,UI挂起.我希望在设备上调用打开"时后台线程会暂停,但在UI线程上不会.我正在测试,而没有后台线程的UI交互.我不知道如何调试该问题,而且这个问题涉及面太广,但也许以前有人见过这种情况.据我所知,ActiveX互操作没有错,该设备可以正常工作.这是一般的方法:
I am using a background thread to initialize an instrument over USB. The UI hangs when I try to open the device. I would expect the background thread to pause when calling Open on the device, but not the UI thread. I am testing this with no UI interaction from the background thread. I don't know how to debug the problem, and it's too broad a question, but perhaps someone has seen something like this before. There is nothing wrong with the ActiveX interop as far as I know, the device works correctly. This is the general approach:
using System;
using FancyVoltmeterLibrary;
namespace SOQuestion
{
public class MeterClass
{
private FancyVoltmeter meter;
private Thread meterThread;
public MeterClass()
{
// Create instance of ActiveX/COM object.
meter = new FancyVoltmeter();
meterThread = new Thread(UpdateMeter);
meterThread.Name = "Meter Thread";
meterThread.Priority = ThreadPriority.Normal;
meterThread.IsBackground = true;
meterThread.Start();
}
private void UpdateMeter()
{
while(true)
{
Thread.Sleep(1000);
if(!meter.IsOpen())
{
// Meter may be powered off here.
// The call to Open takes about 1 second.
// UI hangs during the call???
meter.Open();
}
// code to read meter goes here.
}
}
}
}
也许不清楚我的意思.通过挂起",我应该说暂时冻结".
Perhaps unclear what I meant. By 'hang' I should say 'freezes momentarily'.
推荐答案
电表是否需要在STA中运行?出于这个原因,实际上是将对Open()的调用编组回UI线程吗?
Does meter require running in an STA? Is the call to Open() actually being marshalled back to the UI thread for this reason?
您可以通过在调试器中查看挂起的UI线程的调用堆栈来确认这是正确的.
You can verify this is true by looking at the callstack of the hung UI thread in the debugger.
这篇关于后台线程如何将UI线程挂起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!