The C# app searches for a matching string in a folder with various excel files, each file with various rows and there might be various match strings found in each file. The result will be kept in a global variable. it worked perfectly
without async task but when I tried async/await, the global variable receive some wrong result. can I know how to solve this problem.
public IList<SearchList> SearchResult { get; private set; }
public async Task ReadExcelData(string stringSearch)
{
string filePath = Path.Combine("D:/test/", "Packing List Folder");
SearchResult = new List<SearchList>();
string[] fileArray = Directory.GetFiles(filePath, "*.xls*", SearchOption.AllDirectories);
List<Task> tasks = new List<Task>();
foreach (var file in fileArray)
{
tasks.Add(Task.Run(() => GetXlData(file, stringSearch)));
}
await Task.WhenAll(tasks);
}
private void GetXlData(string file, string stringSearch)
{
using (ExcelEngine excelEngine = new ExcelEngine())
{
// open the file and read every cells here.
if (str == stringSearch)
{
PList =sheet[row, col].Value2;
unit =sheet[row, col+2].Value2;
WriteData(PList, unit);
}
workbook.Close();
stream.Close();
}//how to made a return SearchResult in each task??
private void WriteData(string cde, string unt)
{
SearchResult.Add(new SearchList
{
Code = cde,
Unit = unt,
});
}
public class SearchList
{
public string Code { get; set; }
public string Unit { get; set; }
public override string ToString()
{
return Code;
}
}
this is the app structure I made..
question from:
https://stackoverflow.com/questions/65880398/in-c-sharp-async-and-await-the-global-variable-crashed 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…