微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

附加到计时器调用的异步方法中的文件

如何解决附加到计时器调用的异步方法中的文件

我正在尝试使用

using (StreamWriter sw = File.AppendText(filePath))
{
    sw.WriteLine(n.InnerText);
}

在我认为必须是异步的方法中,因为它正在调用异步方法GetByteArrayAsync()

上的await

投票网站功能

private async void PollSite(string filePath,string siteURL)
{
    response = await http.GetByteArrayAsync(siteURL);
    source = WebUtility.HtmlDecode(Encoding
        .GetEncoding("utf-8")
        .GetString(response,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,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();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。