【发布时间】:2019-04-25 21:12:55
【问题描述】:
我创建了一个 C# Windows IoT 后台应用程序。该应用程序在 ThreadPool 中有多个无限期运行的线程。
这些线程需要能够读取/写入主线程中的全局变量,但我不知道如何实现这一点。这是我正在尝试做的一个示例:
// main task
public sealed class StartupTask : IBackgroundTask
{
private static BackgroundTaskDeferral _Deferral = null;
private static MyThreadClass1 thread1 = null;
private static MyThreadClass2 thread2 = null;
private static MyThreadClass3 thread3 = null;
List<Object> MyDevices = null;
public async void Run(IBackgroundTaskInstance taskInstance)
{
_Deferral = taskInstance.GetDeferral();
MyDevices = GetDeviceList();
thread1 = new MyThreadClass1();
await ThreadPool.RunAsync(workItem =>
{
thread1.Start();
});
thread2 = new MyThreadClass2();
await ThreadPool.RunAsync(workItem =>
{
thread2.Start();
});
thread3 = new MyThreadClass3();
await ThreadPool.RunAsync(workItem =>
{
thread3.Start();
});
}
}
internal class MyThreadClass1
{
public async void Start()
{ }
}
internal class MyThreadClass2
{
public async void Start()
{ }
}
internal class MyThreadClass3
{
public async void Start()
{ }
}
在正在运行的三个线程中的任何一个中,我都需要能够读写List<Object> MyDevices。
线程都有不同的功能,但它们都与“MyDevices”交互,所以如果一个线程对该列表进行了更改,其他线程需要立即知道更改。
最好的方法是什么?
谢谢!
【问题讨论】:
-
C# 中没有全局变量——只有
static类中的字段。或多或少相同,但不同。
标签: c# multithreading iot windows-10-iot-core