gpt4 book ai didi

c# - Windows IoT上的多线程导致线程关闭

转载 作者:行者123 更新时间:2023-12-03 13:07:48 24 4
gpt4 key购买 nike

我是为Windows IoT编写应用程序的新手。我有一个Windows IoT后台应用程序,我想从主线程中生成三个单独的线程。 (我希望它们都在单独的后台线程中运行的原因是因为它们将要进行的某些工作很耗时,所以我显然不想阻塞任何东西)。

第一个线程正在运行小型Web服务器。

第二个线程正在监听Raspberry PI上的GPIO引脚。

第三个线程是通过I2C监听设备。

由于某种原因,我似乎无法使所有三个线程保持打开状态。这是我来自StartupTask的代码:

public sealed class StartupTask : IBackgroundTask
{
private static BackgroundTaskDeferral _Deferral = null;
public async void Run(IBackgroundTaskInstance taskInstance)
{
_Deferral = taskInstance.GetDeferral();

// do some stuff on the main thread here...

// thread 1
var webserver = new TestWebserver();
await ThreadPool.RunAsync(workItem =>
{
webserver.Start();
});

// thread 2
var masterEventListener = new MasterEventListener();
await ThreadPool.RunAsync(workItem =>
{
masterEventListener.Start();
});

// thread 3
var i2cEventListener = new I2CEventListener();
await ThreadPool.RunAsync(workItem =>
{
i2cEventListener.Start();
});
}
}

这是第一个线程的 shell :
internal class TestWebserver
{
private const uint BufferSize = 8192;
public async void Start()
{
var listener = new StreamSocketListener();
await listener.BindServiceNameAsync(8081);

listener.ConnectionReceived += async (sender, args) =>
{
var request = new StringBuilder();
using (var input = args.Socket.InputStream)
{
var data = new byte[BufferSize];
IBuffer buffer = data.AsBuffer();
var dataRead = BufferSize;

while (dataRead == BufferSize)
{
await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
dataRead = buffer.Length;
}
}

using (var output = args.Socket.OutputStream)
{
using (var response = output.AsStreamForWrite())
{
string html = "TESTING RESPONSE";
using (var bodyStream = new MemoryStream(html))
{
var header = $"HTTP/1.1 200 OK\r\nContent-Length: {bodyStream.Length}\r\n\r\nConnection: close\r\n\r\n";
var headerArray = Encoding.UTF8.GetBytes(header);
await response.WriteAsync(headerArray, 0, headerArray.Length);
await bodyStream.CopyToAsync(response);
await response.FlushAsync();
}
}
}
};
}
}

这是第二个线程的 shell :
internal class MasterEventListener
{
public void Start()
{
GpioController gpio = GpioController.GetDefault();
GpioPin gpioPin = gpio.OpenPin(4); // pin4

if (gpioPin.IsDriveModeSupported(GpioPinDriveMode.InputPullUp))
{
gpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
}
else
{
gpioPin.SetDriveMode(GpioPinDriveMode.Input);
}

gpioPin.Write(GpioPinValue.High);
gpioPin.DebounceTimeout = TimeSpan.FromMilliseconds(25);
gpioPin.ValueChanged += Pin_ValueChanged;
}

private void Pin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
{
bool value = sender.Read() == GpioPinValue.High;

if (value)
{
Debug.WriteLine("OPEN!");
}
else
{
Debug.WriteLine("CLOSED!");
}
}
}

这是第三个线程的 shell :
internal class I2CEventsListener
{
public async void Start()
{
string aqs = I2cDevice.GetDeviceSelector();
DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(aqs);

I2CThreadListener(dis);
}

private async void I2CThreadListener(DeviceInformationCollection dis)
{
while(true)
{
var settings = new I2cConnectionSettings(3); // I2C address 3
settings.BusSpeed = I2cBusSpeed.FastMode;
settings.SharingMode = I2cSharingMode.Shared;

using (I2cDevice device = await I2cDevice.FromIdAsync(dis[0].Id, settings))
{
if (device != null)
{
try
{
byte[] writeBuffer = Encoding.ASCII.GetBytes("000000");
byte[] readBuffer = new byte[7];

device.Write(writeBuffer);
device.Read(readBuffer);

var str = Encoding.Default.GetString(readBuffer);
if (str != null && str.Trim().Length == 7 && Convert.ToInt32(readBuffer[0]) > 0)
{
Debug.WriteLine("RESULTS! '" + str + "'");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
}
}
}
Thread.Sleep(100);
}
});
}

如果我注释掉这两个线程中的任何一个,则其余线程将无限期运行并完美运行。

如果我注释掉一个线程,则其余两个线程可以正常工作(有时)约30秒,然后其中一个线程将终止,并显示以下消息:
The thread 0xad0 has exited with code 0 (0x0).

我从未在日志中收到任何错误消息,所以我不相信会引发任何类型的错误。

而且我看到了我期望的结果-只要我只运行其中一个线程即可。但是,一旦我有多个线程一起运行,就会引起问题。

任何方向将不胜感激。

谢谢你们...

最佳答案

根据您的更新代码,尽管由于I2C线程中的while循环阻止了Run方法退出,所以本地类变量(网络服务器等)将始终有效。并且I2C的所有必需变量都在while循环中线程化,以便它们将始终有效。但是本地变量(如listenergpiogpioPin)将由GC收集,并在方法执行完成后不再有效。然后线程将退出。

为了解决这个问题,我对您的代码进行了一些编辑,并且可以正常工作。您可以试试看:

public sealed class StartupTask : IBackgroundTask
{
private static BackgroundTaskDeferral _Deferral = null;
private static TestWebserver webserver = null;
private static MasterEventListener masterEventListener = null;
private static I2CEventsListener i2cEventListener = null;

public async void Run(IBackgroundTaskInstance taskInstance)
{
_Deferral = taskInstance.GetDeferral();

// do some stuff on the main thread here...

// thread 1
webserver = new TestWebserver();
await Windows.System.Threading.ThreadPool.RunAsync(workItem =>
{
webserver.Start();
});

// thread 2
masterEventListener = new MasterEventListener();
await Windows.System.Threading.ThreadPool.RunAsync(workItem =>
{
masterEventListener.Start();
});

// thread 3
i2cEventListener = new I2CEventsListener();
await Windows.System.Threading.ThreadPool.RunAsync(workItem =>
{
i2cEventListener.Start();
});

Debug.WriteLine("The Run method exit...");
}

internal class TestWebserver
{
private StreamSocketListener listener = null;
private const uint BufferSize = 8192;
public async void Start()
{
listener = new StreamSocketListener();
await listener.BindServiceNameAsync("8081");

listener.ConnectionReceived += async (sender, args) =>
{
var request = new StringBuilder();
using (var input = args.Socket.InputStream)
{
var data = new byte[BufferSize];
IBuffer buffer = data.AsBuffer();
var dataRead = BufferSize;

while (dataRead == BufferSize)
{
await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
dataRead = buffer.Length;
}
}

using (var output = args.Socket.OutputStream)
{
using (var response = output.AsStreamForWrite())
{
string html = "TESTING RESPONSE";
using (var bodyStream = new MemoryStream(Encoding.ASCII.GetBytes(html)))
{
var header = $"HTTP/1.1 200 OK\r\nContent-Length: {bodyStream.Length}\r\n\r\nConnection: close\r\n\r\n";
var headerArray = Encoding.UTF8.GetBytes(header);
await response.WriteAsync(headerArray, 0, headerArray.Length);
await bodyStream.CopyToAsync(response);
await response.FlushAsync();
}
}
}
};
}
}

internal class MasterEventListener
{
private GpioController gpio = null;
private GpioPin gpioPin = null;

public void Start()
{

gpio = GpioController.GetDefault();
gpioPin = gpio.OpenPin(4); // pin4

if (gpioPin.IsDriveModeSupported(GpioPinDriveMode.InputPullUp))
{
gpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
}
else
{
gpioPin.SetDriveMode(GpioPinDriveMode.Input);
}

gpioPin.Write(GpioPinValue.High);
gpioPin.DebounceTimeout = TimeSpan.FromMilliseconds(25);
gpioPin.ValueChanged += Pin_ValueChanged;
}

private void Pin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
{
bool value = sender.Read() == GpioPinValue.High;

if (value)
{
Debug.WriteLine("OPEN!");
}
else
{
Debug.WriteLine("CLOSED!");
}
}
}

internal class I2CEventsListener
{
public async void Start()
{
string aqs = I2cDevice.GetDeviceSelector();
DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(aqs);

I2CThreadListener(dis);
}

private async void I2CThreadListener(DeviceInformationCollection dis)
{
var settings = new I2cConnectionSettings(3); // I2C address 3
settings.BusSpeed = I2cBusSpeed.FastMode;
settings.SharingMode = I2cSharingMode.Shared;

I2cDevice device = await I2cDevice.FromIdAsync(dis[0].Id, settings);
if (null == device)
{
Debug.WriteLine("Get I2C device is NULL. Exiting...");
}

byte[] writeBuffer = Encoding.ASCII.GetBytes("000000");
byte[] readBuffer = new byte[7];

while (true)
{
try
{
device.Write(writeBuffer);
device.Read(readBuffer);

var str = Encoding.Default.GetString(readBuffer);
if (str != null && str.Trim().Length == 7 && Convert.ToInt32(readBuffer[0]) > 0)
{
Debug.WriteLine("RESULTS! '" + str + "'");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
}

Thread.Sleep(100);
}
}
}


}

建议使用线程池创建 短期的工作项。请参阅“ Best practices for using the thread pool”。

对于 长时间运行的任务,对于您的情况,如果您的三个线程没有相互通信,则可以为每个任务单独创建一个 background application

关于c# - Windows IoT上的多线程导致线程关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55757220/

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