0

问题是,文档中只写入了一部分而不是所需数量的标题。控制台输出正常。

这里代码:

using AngleSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace AngleSharp

{
    class Program
    {
        static void Main(string[] args)
        {
             Console.WriteLine("ok start");
             Mainpar();
             Console.ReadKey();
        }
    static async Task Mainpar()
    {
        // Setup the configuration to support document loading
        var config = Configuration.Default.WithDefaultLoader();
        // Load the names of all The Big Bang Theory episodes from Wikipedia
        var address = "https://en.wikipedia.org/wiki/List_of_The_Big_Bang_Theory_episodes";
        // Asynchronously get the document in a new context using the configuration
        var document = await BrowsingContext.New(config).OpenAsync(address);
        // This CSS selector gets the desired content
        var cellSelector = "tr.vevent td:nth-child(3)";
        // Perform the query to get all cells with the content
        var cells = document.QuerySelectorAll(cellSelector);
        // We are only interested in the text - select it with LINQ
        var titles = cells.Select(m => m.TextContent).ToArray();

        var allnum = titles.Count();

        System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\bd.txt");
        for (int i = 0; i <= allnum; i++)
        {
          sw.WriteLine(titles[i] + i);
          Console.WriteLine(titles[i] + i);
        }      
      }
   }
}

不知道是什么问题。文件中写入了不同数量的标题,而后者不完全。可能线程被阻塞或程序简单地关闭..我不明白它是如何依赖的

4

1 回答 1

0

您应该正确关闭流。可能发生的情况是,当您的程序关闭而不刷新到文件时,流被强制关闭。尝试包装在 using 语句中:

    using (var sw = new System.IO.StreamWriter(@"C:\bd.txt"))
    {
        for (int i = 0; i <= allnum; i++)
        {
            sw.WriteLine(titles[i] + i);
            Console.WriteLine(titles[i] + i);
        }
    }

using语句确保流正确关闭并在您完成使用时刷新到磁盘。

另外,因为您没有awaitMainPar方法中使用,也没有在 main 方法中调用它await,所以没有充分的理由标记它async。它应该只是static void。除非您异步调用它,否则仅将async关键字添加到方法中没有帮助。如果您想MainPar真正异步,可以使用以下StreamWriter.WriteLineAsync(string)方法:

    using (var sw = new System.IO.StreamWriter(@"C:\bd.txt"))
    {
        for (int i = 0; i <= allnum; i++)
        {
            await sw.WriteLineAsync(titles[i] + i);
            Console.WriteLine(titles[i] + i);
        }
    }

然后您可以像这样在 Main 方法中调用它:

    static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            Console.WriteLine("ok start");
            await Mainpar();
            Console.ReadKey();
        }).GetAwaiter().GetResult();
    }
于 2017-03-15T14:52:32.723 回答