锁()的静态方法 [英] Lock() in a static method

查看:99
本文介绍了锁()的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有写入使用静态方法设置xml文件的多线程应用程序。我想避免该文件是在同一时间内更新两次(导致accesss /写除外)。



我该怎么办呢?



这不工作:

 命名空间计划
{
公共类设置
{
私有静态无效SetSettingsValue(字符串设置字符串值)
{
//使这个线程安全的,以避免写入锁定的设置xml文件
锁(typeof运算(设置))
{
//将数据写入XML文件
}
}
}
}


解决方案

锁()的概念是使用现有对象可以参考和,用于控制是否授予访问权

 静态对象的自旋锁=新的对象(); 

锁(自旋锁)
{
//声明
}

在执行离开锁()块引用被释放,并且任何其他线程正在等待执行代码块可以继续(一次一个,当然)


I have a multi threaded application that writes to a settings xml file using a static method. I want to avoid that the file is being updated twice at the same time (causing accesss/write exception).

How do I do that?

This doesn't work:

namespace Program
{
    public class Settings
    {
        private static void SetSettingsValue (string settings, string value)
        {
            // make this thread safe to avoid writing to a locked settings xml file
            lock (typeof(Settings))
            {
                //write data to xml file
            }
        }
    }
}

解决方案

The concept of lock() is to use an existing-object it can reference and use to control whether access is granted.

static object SpinLock = new object();

lock(SpinLock)
{
   //Statements
}

When the execution leaves the lock() block the reference is released and any other threads waiting to execute the code block can proceed (one at a time, of course).

这篇关于锁()的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆