c# - 在计时器调用的异步方法中附加到文件
问题描述
我正在尝试使用
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine(n.InnerText);
}
在我认为必须是异步的方法中,因为它在异步方法上调用等待GetByteArrayAsync()
投票站功能:
private async void PollSite(string filePath, string siteURL)
{
response = await http.GetByteArrayAsync(siteURL);
source = WebUtility.HtmlDecode(Encoding
.GetEncoding("utf-8")
.GetString(response, 0, response.Length - 1));
result = new HtmlDocument();
result.LoadHtml(source);
gNode = result.GetElementbyId("SomeTable");
using (StreamWriter sw = File.AppendText(filePath))
{
foreach (HtmlNode n in gNode.Descendants("td"))
{
sw.WriteLine(n.InnerText);
}
}
}
试图写给我的错误:
进程无法访问文件“
filePath
”,因为它正被另一个进程使用。
我假设这是因为异步调用,但不知道如何解决这个问题并实现文件写入 - 是因为using
声明吗?
解决方案
只需制作一个信号量并等待。
private readonly SemaphoreSlim _gate = new SemaphoreSlim(1);
private async void PollSite(string filePath, string siteURL)
{
response = await http.GetByteArrayAsync(siteURL);
source = WebUtility.HtmlDecode(Encoding
.GetEncoding("utf-8")
.GetString(response, 0, response.Length - 1));
result = new HtmlDocument();
result.LoadHtml(source);
var gNode = result.GetElementbyId("SomeTable");
await _gate.WaitAsync();
try
{
using (var sw = File.AppendText(filePath))
{
foreach (var n in gNode.Descendants("td"))
{
sw.WriteLine(n.InnerText);
}
}
}
finally
{
_gate.Release();
}
}
推荐阅读
- dart - 使用 AngularDart 组件在列表中打开展开的项目
- java - DropWizard:如果被 100 个请求淹没,为什么它会忽略连接?
- python - 取消嵌套列表
- java - 当我在 jquery 中调用它的内容时,div 标签没有显示
- angular - EACCES 权限被拒绝在 docker 中构建 angular cling
- java - Java:使用 Stream API 在嵌套列表中查找常见项目
- python - 我怎样才能推送到 Heroku
- python - 错误:赋值前引用的变量
- javascript - 简短地突出显示输入中的文本
- python - Python xgboost:内核死了