简体   繁体   中英

I can't figure out how to populate a List<string> inside a c# Task correctly

I wrote this absurd code just to get some clarity:

  • Does it make a difference if I use CallingFunctionAsync_v1 versus CallingFunctionAsync_v2 ?

If so, can someone explain why?

Definitions:

class WorkHorse
{
    const int RECORD_SIZE = 12;

    public async Task<List<string>> DoTheThingAsync_v1(CancellationToken cancellationToken)
    {

        List<string> theList = new List<string>();

        byte[] buffer = new byte[RECORD_SIZE];

        using var fs = File.OpenRead("awesome_stuff.bin");
        int read;
        while ((read = await fs.ReadAsync(buffer, 0, RECORD_SIZE, cancellationToken).ConfigureAwait(false)) != 0)
        {
            theList.Add(Encoding.UTF8.GetString(buffer, 0, RECORD_SIZE));
        }

        return theList;
    }

    public async Task DoTheThingAsync_v2(List<string> theList, CancellationToken cancellationToken)
    {
        byte[] buffer = new byte[RECORD_SIZE];

        using var fs = File.OpenRead("awesome_stuff.bin");
        int read;
        while ((read = await fs.ReadAsync(buffer, 0, RECORD_SIZE, cancellationToken).ConfigureAwait(false)) != 0)
        {
            theList.Add(Encoding.UTF8.GetString(buffer, 0, RECORD_SIZE));
        }
    }
}

Usage:

class FunTimes
{
    List<string> TheStrings;

    public async Task CallingFunctionAsync_v1(CancellationToken cancellationToken)
    {
        this.TheStrings = await new WorkHorse().DoTheThingAsync_v1(cancellationToken).ConfigureAwait(false);
    }

    public Task CallingFunctionAsync_v2(CancellationToken cancellationToken)
    {
        this.TheStrings = new List<string>();
        return new WorkHorse().DoTheThingAsync_v2(this.TheStrings, cancellationToken);
    }

}

V1 is the better approach. It is a pure, blackbox function, which always returns a new list.

V2 expects an initialized instance of List<string> , which is error-prone. You can easily pass null and have an issue. Then, since these are async methods, you can run V2 concurrently and you will have race conditions over the list you have passed.

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