C#以Synchronized多线程安全方式访问流(TextReader、TextWriter、StreamWriter、StreamReader)

在复制内存时检测到可能的 I/O 争用条件。默认情况下,I/O 包不是线程安全的。在多线程应用程序中,必须以线程安全方式(如 TextReader 或 TextWriter 的 Synchronized 方法返回的线程安全包装)访问流。这也适用于 StreamWriter 和 StreamReader 这样的类。

 

public Form1()

{

    InitializeComponent();

    int time = 0;

    int.TryParse(textBox1.Text, out time);

    Stopwatch sw = new Stopwatch();

    sw.Start();

    string filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"cp.bin";//设置路径

    using (FileStream fs = File.Create(filePath))//优化

    {

        double t0 = 0, f0 = 100000, t1 = 1.048576 * 4, f1 = 1000000;

        double beta = (f1 - f0) / t1;

        double chirp = 0;

        Parallel.For(0, 167772160, (i) =>

        {

            t0 += 2.5 * Math.Pow(10, -8);

            chirp = Math.Cos(Math.PI * (2 * f0 + beta * t0) * t0);

            chirp = Math.Round(chirp * 2046);

            chirp = chirp * 2 + 2046;

            byte[] b = Encoding.Unicode.GetBytes(chirp.ToString());

            fs.Write(b, 0, b.Length);

        });

    }

    sw.Stop();

   textBox1.Text ="耗时为:  " +sw.ElapsedMilliseconds.ToString()+"  ms";

}

错误信息:在复制内存时检测到可能的 I/O 争用条件。默认情况下,I/O 包不是线程安全的。在多线程应用程序中,必须以线程安全方式(如 TextReader 或 TextWriter 的 Synchronized 方法返回的线程安全包装)访问流。这也适用于 StreamWriter 和 StreamReader 这样的类。

 

运行的时候会出现这样的错误,该如何解决呢,我不太懂Parallel.For并行运算,谢谢啊,急等

 

===================================================================

从你的错误信息看,你需要使用内置的 Syncronized TextReader/Writer类。你可以尝试修改你的代码如下:

 

Stopwatch sw = new Stopwatch();

sw.Start();

string filePath = @"D:\cp.bin";// 

using (FileStream fs = File.Create(filePath))// 

{

    StreamWriter ObjWrites = default(StreamWriter);

    ObjWrites = new StreamWriter(fs);

    dynamic synws = StreamWriter.Synchronized(ObjWrites);

 

    double t0 = 0, f0 = 100000, t1 = 1.048576 * 4, f1 = 1000000;

    double beta = (f1 - f0) / t1;

    double chirp = 0;

    Parallel.For(0, 1677, (i) =>

    {

        t0 += 2.5 * Math.Pow(10, -8);

        chirp = Math.Cos(Math.PI * (2 * f0 + beta * t0) * t0);

        chirp = Math.Round(chirp * 2046);

        chirp = chirp * 2 + 2046;

 

        //byte[] b = Encoding.Unicode.GetBytes(chirp.ToString());

        //synws.Write(b, 0, b.Length);

        synws.Write(chirp.ToString());

    });

    synws.Close();

    ObjWrites.Close();

}

sw.Stop();

MessageBox.Show("耗时为:  " + sw.ElapsedMilliseconds.ToString() + "  ms");

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值