C# 在一个线程和另一个线程中写入xml文件-如何安全地重新启动?
我在一个线程中写入xml文件,在另一个线程中重新启动。有一种方法可以确保在重新启动之前写入xml 正如您所说,您正在线程中编写xml。你可以用C# 在一个线程和另一个线程中写入xml文件-如何安全地重新启动?,c#,xml,multithreading,C#,Xml,Multithreading,我在一个线程中写入xml文件,在另一个线程中重新启动。有一种方法可以确保在重新启动之前写入xml 正如您所说,您正在线程中编写xml。你可以用 Thread1.IsAlive //Property 它将指示线程已完成或仍在编写xml文件 if (Thread1.IsAlive==true) //线程仍然在写 if (Thread1.IsAlive==false) //线程已完成,请重新启动计算机。您可以使用在两个线程之间进行通信 首先声明一个AutoResetEvent并将其初始状态设置
Thread1.IsAlive //Property
它将指示线程已完成或仍在编写xml文件
if (Thread1.IsAlive==true)
//线程仍然在写
if (Thread1.IsAlive==false)
//线程已完成,请重新启动计算机。您可以使用在两个线程之间进行通信
首先声明一个AutoResetEvent并将其初始状态设置为false(无信号)
然后在主线程上,您可以等待事件发出信号
autoEvent.WaitOne(); //wait for the event
//After receiving the signal, you can go on to restart the system
在写入XML文件后的工作线程上,可以向事件发送信号通知主线程,如下所示
//Write to the XML file and close the file, then notify the main thread
autoEvent.Set();
这可以回答“当我完成时如何通知其他线程”的问题。但是您使用工作线程来编写XML文件,因为您希望保持UI响应,对吗?如果主线程在工作线程写入文件时等待信号,则应用程序也无法响应用户交互。
因此,更好的方法是注册回调以等待事件,一旦在工作线程上发出事件信号,回调将重新启动系统
考虑ThreadPool
类,您可以使用QueueUserWorkItem
方法在线程池线程上执行实际工作(写入XML文件),并使用RegisterWaitForSingleObject
方法注册回调,以便在接收到来自线程池的信号时重新启动系统。通过这种方式,您可以保持UI的响应性
代码示例改编自
重新启动是什么意思?我重新启动了系统。如果在使用第三个线程重新启动之前需要两个线程来完成某项任务,我该怎么办?@janneob在WaitHandle数组上使用WaitAll()。您可以在此处找到一个示例:
//Write to the XML file and close the file, then notify the main thread
autoEvent.Set();
class Program
{
static AutoResetEvent ar = new AutoResetEvent(false);
static void Main(string[] args)
{
//register the callback
ThreadPool.RegisterWaitForSingleObject(ar,
new WaitOrTimerCallback(ThreadProc),
null, -1, false);
// Queue the task
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), null);
Console.ReadLine();
}
// This thread procedure performs the task specified by the
// ThreadPool.QueueUserWorkItem
static void ThreadProc(Object stateInfo)
{
//Write to the XML file and close the file, then notify the main thread
ar.Set();
}
// This thread procedure performs the task specified by the
// ThreadPool.RegisterWaitForSingleObject
static void ThreadProc(Object stateInfo, bool timedOut)
{
//restart the system
}
}