S
S
Sergey2021-04-12 20:01:09
.NET
Sergey, 2021-04-12 20:01:09

How to find where NullReferenceException is?

Good afternoon.
Tell me how to catch the elusive null?

There is a program with this method:

private async Task checkFile(string path)
        {
            var fileType = await getFileAsync(path);
            
                if (fileType.FileExtension != "None")
                {
                    try
                    {
                        if (this.filesMap == null) Console.WriteLine("Map is null");
                        if (path == null) Console.WriteLine("path is null");
                        if (fileType == null) Console.WriteLine("type is null");

                        this.filesMap.Add(path, fileType);
                    }
                    catch(Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                    
                }
            
        }


On a sample of 20,000 files, NullReferenceException occurs once out of five launches of the program when adding an element to the filesMap.Add dictionary, at the very beginning of the program, when the map size is two or three elements. Stumbles each time on different files.

All three variables that are contained in this code (path, fileType, filesMap) contain some value at the time of the error, I even set these rightlines to make sure that I didn’t go crazy. They don't output anything to the console.

Also, tri-catch does not automatically handle the error, and the studio stops the program. If you continue, then the exception from the ketch will be displayed in the console, followed by the second same error. Further to the end the program works normally. Mistakes happen only in twos, always in twos. Or none happens.
It feels like something is happening in dictionary.Add() .

The whole code is here: https://github.com/osija/ImgExtractor/blob/master/... Attached

is a picture with an error: 60747be915915833639082.png

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2021-04-12
@Bibort

Heh, so Dictinary is not thread-safe. You need either a thread-safe collection or a lock.
In FileMapper add somewhere And try to rewrite to this
private static object locker = new object();

private async Task checkFile(string path)
        {
            var fileType = await getFileAsync(path);
            
                if (fileType.FileExtension != "None")
                {
                      lock(locker){
                        this.filesMap.Add(path, fileType);
}                    
                }
            
        }

PS Thread-Safe Collections

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question