Problem writing Async file

I have the following testing method in which I test the async file :

[TestMethod]
public async Task TestMethod1()
{
    List<Task> tasks = null;
    int x = 1;
    int step = 10;
    for (int i = step; i <=200; i = i + step)
    {
        tasks = Enumerable.Range(x, step).Select(async y =>
            {
                await TextFile.WriteTextAsync("file.txt", String.Format("{0}\n", y));
            }).ToList();

        x = i + 1;
        await Task.WhenAll(tasks);
    }
}   

Code for recording in Async format:

public static async Task WriteTextAsync(string filePath, string text)
{
    byte[] encodedText = Encoding.Unicode.GetBytes(text);

    using (FileStream sourceStream = new FileStream(filePath,
        FileMode.Append, FileAccess.Write, FileShare.ReadWrite,
        bufferSize: 4096, useAsync: true))
    {
        await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
    };
}

The problem is that my code creates a file that does not contain all the expected values.

I expect to see values ​​from 1 to 200 in the file, but instead I have, for example,

1 
3
5
7
8

12
13
14 
...

See the detailed file here http://bit.ly/1JVMAyg Maybe someone has an idea what is happening and how to fix it?

NOTE. . See my solution below, which fixed the problem with the absence of elements that are not inserted in the file, but it violates the whole idea of ​​multithreading mentioned in the LasseV.Karlsen comment. I am glad to see if anyone has a better solution that does not break multithreading.

+4
1

@JonSkeet. . WriteTextAsync, :

private static SemaphoreSlim _thread= new SemaphoreSlim(1);    
public static async Task WriteTextAsync(string filePath, string text)
{
    byte[] encodedText = Encoding.Unicode.GetBytes(text);
    await _sync.WaitAsync();
    try
    {

        using (FileStream sourceStream = new FileStream(filePath,
            FileMode.Append, FileAccess.Write, FileShare.ReadWrite,
            bufferSize: 4096, useAsync: true))
        {
            await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
        };
    }

    catch(Exception ex)
    {
        Debug.WriteLine(ex.ToString());
    }
    finally
    {
        _thread.Release();
    }
}

: , , WriteTextAsync , , @LasseV.Karlsen.

, , , , - , .

0

All Articles