同步两个计时器

时间:2015-03-20 07:41:17

标签: c# multithreading timer sync windows-forms-designer

我有一个游戏,它使用共享磁盘在txt文件之间传递数据,问题是当我打开2个窗口时,它们互相交错并停止工作。

这里有一些代码:

        private void timer1_Tick(object sender, EventArgs e)
    {
        try
        {
            if (count == 1)
            {
                circle1.setX(circle1.getX() + (int)deltaX[0]);
                circle1.setY(circle1.getY() + (int)deltaZ[0]);
                File.WriteAllText(@"L:\achtung\player1.txt", String.Empty);
                StreamWriter sw = new StreamWriter(@"L:\achtung\player1.txt");
                StreamReader sw1 = new StreamReader(@"L:\achtung\player2.txt");
                sw.WriteLine(circle1.getX());
                sw.WriteLine(circle1.getY());
                sw.Close();
                for (int i = 0; i < 2; i++)
                {
                    if (i == 0)
                        x = Convert.ToInt32(sw1.ReadLine());
                    else
                        y = Convert.ToInt32(sw1.ReadLine());
                }
                sw1.Close();
                circle2.setX(x);
                circle2.setY(y);
            }
            else if (count == 2)
            {
                circle2.setX(circle2.getX() + (int)deltaX[0]);
                circle2.setY(circle2.getY() + (int)deltaZ[0]);
                File.WriteAllText(@"L:\achtung\player2.txt", String.Empty);
                StreamWriter sw = new StreamWriter(@"L:\achtung\player2.txt");
                StreamReader sw1 = new StreamReader(@"L:\achtung\player1.txt");
                sw.WriteLine(circle2.getX());
                sw.WriteLine(circle2.getY());
                sw.Close();
                for (int i = 0; i < 2; i++)
                {
                    if (i == 0)
                        x = Convert.ToInt32(sw1.ReadLine());
                    else
                        y = Convert.ToInt32(sw1.ReadLine());
                }
                sw1.Close();
                circle1.setX(x);
                circle1.setY(y);
            }
        }
        catch (Exception ex)
        {
        }

        System.Drawing.Graphics graphics = this.CreateGraphics();
        graphics.FillEllipse(Brushes.Red, circle1.getX(), circle1.getY(), 10, 7);
        graphics.FillEllipse(Brushes.Gray, circle2.getX(), circle2.getY(), 10, 7);
    }

如何从两个打开的表单中同时读写?

0 个答案:

没有答案