Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 异步文件写入问题_C#_.net_Unit Testing_Asynchronous_Async Await - Fatal编程技术网

C# 异步文件写入问题

C# 异步文件写入问题,c#,.net,unit-testing,asynchronous,async-await,C#,.net,Unit Testing,Asynchronous,Async Await,我有下一个测试方法,我正在测试: 问题是我的代码生成的文件不包含所有预期值 我希望在文件中看到从1到200的值,但是我有 1 3 5 7 8 12 13 14 ... 请参见此处的详细文件 也许有人知道发生了什么,如何解决 注意:请参阅下面我的解决方案,该解决方案解决了文件中未插入缺少项的问题,但它打破了@LasseV.Karlsen在其评论中提到的多线程的整个概念。我很高兴看到有没有更好的解决方案不会破坏多线程。谢谢@JonSkeet。我知道了。我必须限制对“WriteTextAsyn

我有下一个测试方法,我正在测试:

问题是我的代码生成的文件不包含所有预期值

我希望在文件中看到从1到200的值,但是我有

1 
3
5
7
8

12
13
14 
...
请参见此处的详细文件 也许有人知道发生了什么,如何解决


注意:请参阅下面我的解决方案,该解决方案解决了文件中未插入缺少项的问题,但它打破了@LasseV.Karlsen在其评论中提到的多线程的整个概念。我很高兴看到有没有更好的解决方案不会破坏多线程。

谢谢@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所述,在某个时间点只有单线程访问文件


看来我的解决方案解决了这个问题,但打破了多线程的整个概念,我很高兴看到有没有更好的解决方案不会破坏多线程。

您有多个线程同时写入同一个文件。这似乎不太可能很好地结束。但是如果一次只需要一个线程来写入文件,那么为什么要使用整个线程呢?你基本上是在向商店发送N个购物者,但商店只有一行结账,还是我遗漏了什么?@LasseVKarlsen实际上我根本看不到线程……除非默认的调度程序是umm。。默认计划程序。。。
1 
3
5
7
8

12
13
14 
...
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();
    }
}