c# - 是否可以在锁内使用另一个线程来重定向文件中的输出?
问题描述
我有两个使用 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);
}
解决方案
推荐阅读
- django - Django 表单 - 我如何使 ModelChoiceField 仅在选择另一个选择值时才显示数据
- json - 在 Xamarin 表单中解析嵌套的 JSon 文件
- unity3d - OnTriggerCollider 时如何解决游戏冻结问题?
- c# - 使用 LinqKit 和 EFCore 进行预加载
- azure - 是否可以对 Azure VM 上的 IIS 和 Azure 应用服务之间的流量进行负载平衡?
- java - Java 的 ResultSet 实现是否重新执行 SQL 语句以检索额外的 ResultSet 数据
- openid - 使用 OpenID / Keycloak 进行身份验证后,在 micronaut 应用程序中“找不到令牌”
- shell - Xamarin Forms Shell FlyoutItem
- angular - “.builders['browser']”应该有必需的属性'class'
- sap - 在多连接 Universe 中,当从两个数据库中引入对象时,会出现“由于对象不兼容而无法运行查询”错误