在一个线程中写入xml文件并在其他线程重新启动 - 如何安全地执行?

时间:2014-01-05 09:23:07

标签: c# xml multithreading

我正在写一个线程中的xml文件,而另一个线程我正在重启。有一种方法可以确保在重启之前写入xml吗?

2 个答案:

答案 0 :(得分:1)

正如你所说,你正在一个线程中写一个xml。你可以用

Thread1.IsAlive //Property

它将指示您已完成线程或仍在编写xml文件。

if (Thread1.IsAlive==true)

//线程仍然在写。

 if (Thread1.IsAlive==false)

//线程已完成,现在重新启动计算机。

答案 1 :(得分:1)

您可以使用AutoResetEvent在两个主题之间进行通信。

首先声明一个AutoResetEvent并将其初始状态设置为false(非信号)。

AutoResetEvent autoEvent = new 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方法在ThreadPool线程上执行实际工作(编写XML文件),并使用RegisterWaitForSingleObject方法注册回调以重新启动从线程池收到信号时的系统。通过这种方式,您可以保持UI响应。

代码示例改编自Beginners Guide to Threading in .NET: Part 4 of n

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
    }
}