C# 是否可以在锁中使用另一个线程重定向文件中的输出?

C# 是否可以在锁中使用另一个线程重定向文件中的输出?,c#,locking,C#,Locking,我有两个使用lock语句的函数,在某些操作完成后,我将输出重定向到.txt文件中。我已经意识到他们的执行需要很多时间,这导致他们的操作被阻塞,并且总体上降低了应用程序的性能 我认为执行时间长可能是因为将操作写入文件。减少执行时间最有效的方法是什么?我是否应该使用另一个线程进行写操作,是否可以在锁内不持有锁 我的代码的简化版本如下所示: StatsInformation statsInfo = new StatsInformation (); List<int> lIn

我有两个使用lock语句的函数,在某些操作完成后,我将输出重定向到.txt文件中。我已经意识到他们的执行需要很多时间,这导致他们的操作被阻塞,并且总体上降低了应用程序的性能

我认为执行时间长可能是因为将操作写入文件。减少执行时间最有效的方法是什么?我是否应该使用另一个线程进行写操作,是否可以在锁内不持有锁

我的代码的简化版本如下所示:

    StatsInformation statsInfo = new StatsInformation ();
    List<int> lInt = new List<int>();

    public void FunctionEnq(List<byte> lByte, int _int)
    {
        lock (OperationLock)
        {
           //Do some work here 
           lInt.Add(_int);
           string result = "New Int " + _int + " size " + lInt.Count + " time " + DateTime.Now.ToString("hh:mm:ss.fff");
           statsInfo.WriteStatsInFile(result); 
        }
    }

    public (List<byte> _outByte, int _time) FunctionDeq()
    {
        List<byte> _outByte = new List<byte> ();
        int _time = -1;
        lock (OperationLock)
        {
           //Do some work here 
           _outByte.Add(...);
           int _int =  lInt[0];
           //do operations
           _time = _int;
           lInt.RemoveAt(0);
           string result = "Get Int " + _int + " new size " + lInt.Count + " time " + DateTime.Now.ToString("hh:mm:ss.fff");
           statsInfo.WriteStatsInFile(result); 
        }
        return (_outByte, _time);
    }
StatsInformation statsInfo=新StatsInformation();
List lInt=新列表();
公共无效函数ENQ(列表lByte,int _int)
{
锁(操作锁)
{
//在这里做些工作
lInt.Add(_int);
string result=“New Int”+_Int+“size”+lInt.Count+“time”+DateTime.Now.ToString(“hh:mm:ss.fff”);
statinfo.writestatinfile(结果);
}
}
公共(列表输出字节,整数时间)函数deq()
{
List _outByte=新列表();
int _time=-1;
锁(操作锁)
{
//在这里做些工作
_添加(…);
int _int=lInt[0];
//做手术
_时间=_int;
脱绒量(0);
string result=“Get Int”+_Int+“new size”+lInt.Count+“time”+DateTime.Now.ToString(“hh:mm:ss.fff”);
statinfo.writestatinfile(结果);
}
返回(_outByte,_time);
}

您知道吗?。。。和日志框架(Serilog、log4net、NLog…)@Fildor感谢您提供的信息。我知道并发名称空间,但由于一些操作,我更喜欢使用列表,并认为排序等。ConcurrentQueue会降低性能。也许我需要重新考虑,再检查一遍。至于日志框架,我不知道你提到的那些(除了NLog,但从未使用过)。一个能够异步写入的日志框架值得一试,以避免文件I/O损失。另一种选择是使用BlockingQueue,在其中写入日志消息,然后让另一个线程使用它并执行文件I/O。这里的另一件事是受保护的块相当长。我会试着把它们改短些。仅此一点就应该提高绩效。