如果我有那个线程:
Thread sendMessage = new Thread(new ThreadStart(timer.Start()));
请问,定时器的Tick事件是在主线程还是在sendMessage线程?
编辑: 我有一个队列,我希望计时器每 x 毫秒计时一次,程序将从队列中取出数组,但这是我的代码:
Thread sendMessage = new Thread(new ThreadStart(startThreadTimer));
public Queue<Array> messageQueue = new Queue<Array>();
System.Threading.Timer timer;
private void startThreadTimer()
{
System.Threading.TimerCallback cb = new System.Threading.TimerCallback(checkIfQueue);
timer = new System.Threading.Timer(cb, null, 4000, 30);
}
private static void checkIfQueue(object obj)
{
}
而且我不能调用非静态方法或使用 checkIfQueue 中的非静态字段,它必须是静态的,我该怎么办?
编辑: 这是你们中的一个人发给我的代码,我修改了他所以它符合我的目标,它能工作吗?
public ConcurrentQueue<Array> messageQueue = new ConcurrentQueue<Array>();
public void Example()
{
var thread = new Thread(
() =>
{
while (true)
{
Array array;
byte[] byteArray = {};
if (messageQueue.Count > 0)
{
messageQueue.TryDequeue(out array);
foreach (byte result in array)
{
byteArray[byteArray.Length] = result;
}
controllernp.Write(byteArray, 0, 100);
}
Thread.Sleep(30);
}
});
thread.IsBackground = true;
thread.Start();
}
最佳答案
这取决于计时器的类型。大多数可以在后台线程中工作的计时器(System.Timers.Timer 或 System.Threading.Timer)都将 ThreadPool 线程用于它们的 Tick 事件。在这种情况下,答案是“两者都不”。
如果您的计时器是 Windows 窗体计时器或 DispatcherTimer,它可能会导致异常,因为它们需要在 UI 线程上运行,而不能在后台线程上运行。
关于c# - 关于多线程的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3999271/