Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

In C# async and await the global variable crashed

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First option is to use a lock

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement

so you set the lock, access the global variable and release the lock again. So only one thread at a time can write to the variable. But I would not do this. Don't use global variables when dealing with threads.

Second option: A task can return something.

after the Task.WhenAll you can iterate over your tasks and get the results (Result property in the task) and add them to your global variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...