[英]How and where i can apply await in my async method
I am new to async and await in c#. 我是异步新手,正在使用C#等待。 I am trying to read some 300 text files where I am using List which is calling a function "ReadFiles".
我正在尝试在使用List的位置读取300个文本文件,该列表调用函数“ ReadFiles”。 I made this function Async but I don't know how to modify my code now to use await.
我将此功能设为Async,但现在不知道如何修改代码以使用await。 where should I use the await keyword so that it can run my program without throwing an error.
我应该在哪里使用await关键字,以便它可以运行我的程序而不会引发错误。 Any help would be appreciated.
任何帮助,将不胜感激。 Below is my code :
下面是我的代码:
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;
}
You need to make couple of changes. 您需要进行一些更改。
First change the void to Task 首先将void更改为Task
public async Task ReadFile(string file, string folderPath, string folderName, string week)
Second change sw.WriteLine to await sw.WriteLineAsync 第二次更改sw.WriteLine以等待sw.WriteLineAsync
await sw.WriteLineAsync(fileName + " " + "--" + " " + "Line number :" + " " + LineCount);
Finally, call the method as bellow. 最后,将该方法称为波纹管。
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);
Also, you need to synchronize the Filecount variable as: 另外,您需要将Filecount变量同步为:
lock(new object())
{
Filecount++;
}
You will need to change 您将需要改变
public async void ReadFile(string file, string folderPath, string folderName, string week)<br/>
and make it return a Task preferably the value that you want at the end of method. 并使其最好在方法结束时返回Task所需的值。 Since async void used together means fire and forget.
由于异步虚空一起使用,意味着失火。 Which means it will start the execution wont wait for it to complete but execute the rest of statements while continuing execution in background.
这意味着它将开始执行,不会等待它完成,而是在后台继续执行时执行其余语句。 So you will end up receiving
Read the files successfully.
这样您将最终收到
Read the files successfully.
message before you even finish having read file. 消息,甚至没有完成读取文件。
I know this is not directly what you ask, but you should not confuse async/await with multi-threading. 我知道这不是您直接问的问题,但是您不应该将async / await与多线程混淆。 So if what you're after is multiple threads handling different files at the "same time", you should not use async/await.
因此,如果要处理的是多个线程在“同一时间”处理不同的文件,则不应使用async / await。
If this is not what you're after, but what you actually want is async/await, you need to use async methods to actually gain anything from it. 如果这不是您要追求的,但是您真正想要的是异步/等待,则需要使用异步方法实际从中获取任何收益。 So when you call WriteLine/ReadLine on the StreamReader/StreamWriter, you should actually use the WriteLineAsync method and ReadLine async method.
因此,当您在StreamReader / StreamWriter上调用WriteLine / ReadLine时,实际上应该使用WriteLineAsync方法和ReadLine async方法。 Otherwise there's no gain.
否则就没有收获。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.