简体   繁体   中英

Strange dispose behavior while testing

I Have endpoint which use handlers of 2 others endpoints it's probably not best practice, but it's not the point. In this methods I use a lot of MemoryStreams, ZipStream and stuff like that. Of course I dispose all of them. And everything works good till I run all tests together, then tests throw errors like: “Input string was not in a correct format.”, "Cannot read Zip file" or other weird messages. This are also test of this 2 handlers which I use in previous test. Solution what I found is to add "Thread.Sleep(1);" at the end of the "Handle" method, just before return. It looks like something need more time to dispose, but why?. Have you any ideas why this 1ms sleep help with this?

ExtractFilesFromZipAndWriteToGivenZipArchive is an async method.

public async Task<MemoryStream> Handle(MultipleTypesExportQuery request, CancellationToken cancellationToken)
    {
        var stepwiseData = await HandleStepwise(request.RainmeterId, request.StepwiseQueries, cancellationToken); 
        var periodicData = await HandlePeriodic(request.RainmeterId, request.PeriodicQueries, cancellationToken);
        
        var data = new List<MemoryStream>();
        data.AddRange(stepwiseData);
        data.AddRange(periodicData);

        await using (var ms = new MemoryStream())
        using (var archive = new ZipArchive(ms, ZipArchiveMode.Create,false))
        {
            int i = 0;
            foreach (var d in data)
            {
                d.Open();
                d.Position = 0;
                
                var file = ZipFile.Read(d);
                
                ExtractFilesFromZipAndWriteToGivenZipArchive(file, archive, i, cancellationToken);
                
                i++;
                file.Dispose();
                d.Dispose();
            }
            //Thread.Sleep(100);
            return ms;
        }
    }

ExtractFilesFromZipAndWriteToGivenZipArchive() is an asynchronous function which means, in this case, that you need to await it:

await ExtractFilesFromZipAndWriteToGivenZipArchive(file, archive, i, cancellationToken);

Otherwise, the execution will keep going without waiting the function to return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM