gpt4 book ai didi

c# - winform 中的线程 - Compact .NET Framework 3.5

转载 作者:行者123 更新时间:2023-12-03 20:57:55 24 4
gpt4 key购买 nike

我在启动实时监控的函数中有一个线程,它基本上打开串口并不断从串口读取数据。但是,如果我需要终止这个线程,我应该怎么做呢?因为如果我不终止打开特定串口和读取数据的运行线程。当我关闭它并再次调用该函数时。同一个串口打不开。我怀疑串行端口没有正确关闭并且仍在单独的线程中运行。所以我想我必须终止那个线程,以便下次再次打开同一个串行端口。有谁知道如何实现这一点?

我看到一些论坛说 Thread.Abort() 使用起来很危险。它应该只在最后的手段中使用。

感谢您的帮助。

查尔斯

最佳答案

通常,您设计在后台线程中运行的方法来监听取消请求。这可以像 bool 值一样简单:

//this simply provides a synchronized reference wrapper for the Boolean,
//and prevents trying to "un-cancel"
public class ThreadStatus
{
private bool cancelled;

private object syncObj = new Object();

public void Cancel() {lock(syncObj){cancelled = true;}}

public bool IsCancelPending{get{lock(syncObj){return cancelled;}}}
}

public void RunListener(object status)
{
var threadStatus = (ThreadStatus)status;

var listener = new SerialPort("COM1");

listener.Open();

//this will loop until we cancel it, the port closes,
//or DoSomethingWithData indicates we should get out
while(!status.IsCancelPending
&& listener.IsOpen
&& DoSomethingWithData(listener.ReadExisting())
Thread.Yield(); //avoid burning the CPU when there isn't anything for this thread

listener.Dispose();
}

...

Thread backgroundThread = new Thread(RunListener);
ThreadStatus status = new ThreadStatus();
backgroundThread.Start(status);

...

//when you need to get out...
//signal the thread to stop looping
status.Cancel();
//and block this thread until the background thread ends normally.
backgroundThread.Join()

关于c# - winform 中的线程 - Compact .NET Framework 3.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10020056/

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