首页 > 解决方案 > 在计时器调用的异步方法中附加到文件

问题描述

我正在尝试使用

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声明吗?

标签: c#async-awaitstreamwriter

解决方案


只需制作一个信号量并等待。

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();
    }
}

推荐阅读