c# 多线程 读取 app.config 的时候 ,出现被使用怎么处理?

2025-04-19 17:17:56
推荐回答(1个)
回答1:

这个得加锁,不然就会出现这个问题。

 

假设我在App.Config文件中添加以下数据:


  
  

然后我们开10个线程同时读取这两条数据,5个线程读取hello1,5个线程读取hello2的值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Configuration;
namespace ReadWriteOneFileSync
{
    class Program
    {
        protected ReaderWriterLockSlim _readwriteLock = new ReaderWriterLockSlim();
        static void Main(string[] args)
        {
            Program prog = new Program();
            for (int i = 0; i < 10; i++)
            {
                string key = "hello" + (1 + (i % 2)).ToString();
                Thread t = new Thread(prog.ReadFromConfiguration);
                t.Start(key);
                t.Join();
            }
            Console.ReadLine();
        }
        public void ReadFromConfiguration(object key)
        {
            _readwriteLock.EnterReadLock();
            string value = String.Empty;
            try
            {
                value = ConfigurationSettings.AppSettings[key.ToString()].ToString();
                Console.WriteLine(value);
            }
            finally
            {
                _readwriteLock.ExitReadLock();
            }
        }
    }
}

 输出结果:

Hello World 1
Hello World 2
Hello World 1
Hello World 2
Hello World 1
Hello World 2
Hello World 1
Hello World 2
Hello World 1