我可以在异步方法中应用await的方式和位置

时间:2016-02-04 06:05:11

标签: c#

我是async的新手并在c#中等待。我正在尝试阅读大约300个文本文件,其中我正在使用List来调用函数" ReadFiles"。我将此功能设为Async,但我现在还不知道如何修改我的代码以使用await。我应该在哪里使用await关键字,以便它可以运行我的程序而不会抛出错误。任何帮助,将不胜感激。以下是我的代码:

List<Task> tasks = new List<Task>();
foreach (var file in folderFiles)
{
    var task = Task.Factory.StartNew(() =>
    {
         ReadFile(file.FullName, folderPath, folder.Name, week);
    });
    tasks.Add(task);
}

Task.WaitAll(tasks.ToArray());
DateTime stoptime = DateTime.Now;
TimeSpan totaltime = stoptime.Subtract(starttime);
label6.Text = Convert.ToString(totaltime);
textBox1.Text = folderPath;
DialogResult result2 = MessageBox.Show("Read the files successfully.", "Important message", MessageBoxButtons.OK, MessageBoxIcon.Information);

public async void ReadFile(string file, string folderPath, string folderName, string week)
{
    int LineCount = 0;
    string fileName = Path.GetFileNameWithoutExtension(file);

    using (FileStream fs = File.Open(file, FileMode.Open))
    using (BufferedStream bs = new BufferedStream(fs))
    using (StreamReader sr = new StreamReader(bs))
    {
        for (int i = 0; i < 2; i++)
        {
            sr.ReadLine();
        }

        string oline;
        while ((oline = sr.ReadLine()) != null)
        {
            LineCount = ++LineCount;
            string[] eachLine = oline.Split(';');

            string date = eachLine[30].Substring(1).Substring(0, 10);

            DateTime dt;

            bool valid = DateTime.TryParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

            if (!valid)
            {
                Filecount = ++Filecount;
                StreamWriter sw = new StreamWriter(folderPath + "/" + "Files_with_wrong_date_format_" + folderName + ".txt", true);
                sw.WriteLine(fileName + "  " + "--" + "  " + "Line number :" + " " + LineCount);
                sw.Close();
            }
            else
            {
                DateTime Date = DateTime.ParseExact(date, "d/M/yyyy", CultureInfo.InvariantCulture);

                int calculatedWeek = new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(Date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Saturday);

                if (calculatedWeek == Convert.ToInt32(week))
                {

                }
                else
                {
                    Filecount = ++Filecount;
                    StreamWriter sw = new StreamWriter(folderPath + "/" + "Files_with_dates_mismatching_the_respective_week_" + folderName + ".txt", true);
                    sw.WriteLine(fileName + "  " + "--" + "  " + "Line number :" + " " + LineCount);
                    sw.Close();
                }
            }       
        }
    }
    //return true;
}

3 个答案:

答案 0 :(得分:1)

您需要进行一些更改。

首先将void更改为Task

public async Task ReadFile(string file, string folderPath, string folderName, string week)

第二次改变sw.WriteLine以等待sw.WriteLineAsync

await sw.WriteLineAsync(fileName + "  " + "--" + "  " + "Line number :" + " " + LineCount);

最后,调用方法如下。

List<Task> tasks = new List<Task>();
        foreach (var file in folderFiles)
        {
            var task = ReadFile(file.FullName, folderPath, folder.Name, week);
            tasks.Add(task);
        }
        Task.WhenAll(tasks);

此外,您需要将Filecount变量同步为:

lock(new object())
{
     Filecount++;
}

答案 1 :(得分:0)

您需要更改

public async void ReadFile(string file, string folderPath, string folderName, string week)<br/>

并使其返回一个Task,最好是方法结束时所需的值。 由于异步空白一起使用意味着火和忘记。这意味着它将开始执行,不会等待它完成,但执行其余的语句,同时继续在后台执行。因此,在完成阅读文件之前,您最终会收到Read the files successfully.消息。

答案 2 :(得分:0)

我知道这不是你要求的,但你不应该将async / await与多线程混淆。因此,如果您追求的是多个线程在同一时间处理不同的文件&#34;,则不应使用async / await。

如果这不是你所追求的,但你真正想要的是async / await,你需要使用异步方法来实际获得任何东西。因此,当您在StreamReader / StreamWriter上调用WriteLine / ReadLine时,您应该实际使用WriteLineAsync方法和ReadLine异步方法。否则就没有收获。