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

我有两个使用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);
    }
qiyugfh0715021 回答:是否可以在锁中使用另一个线程来重定向文件中的输出?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3137243.html

大家都在问