首页 > 解决方案 > 是否可以在锁内使用另一个线程来重定向文件中的输出?

问题描述

我有两个使用 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);
    }

标签: c#locking

解决方案


推荐阅读