用于操纵杆输入的多线程

时间:2014-06-02 21:51:09

标签: c# multithreading sharpdx

您好,我正在尝试制作问题答案游戏。 (按下操纵杆按钮的人首先回答问题)

到目前为止,我已经使用了SharpDX,因为我无法通过SharpDX处理按钮按下事件

我的问题是我不能让它奏效。我不知道原因,但让我解释一下我的代码。

在我的页面加载中,我已经初始化了2个不同的线程;

//Initializing the constants 

    private bool q = true;
    private Thread th1;
    private Thread th2;
    private Guid joy1Guid = Guid.Empty;
    private Guid joy2Guid = Guid.Empty;
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        var directInput = new DirectInput();

        foreach (var deviceInstance in directInput.GetDevices())
        {
            if (deviceInstance.Subtype == 258)
            {


//My joysticks connected to pc via usb.
                if (joy1Guid == Guid.Empty)
                    joy1Guid = deviceInstance.InstanceGuid;
                else if (joy2Guid == Guid.Empty)
                    joy2Guid = deviceInstance.InstanceGuid;
            }
        }

        th1 = new Thread(Joy1Start);
        th2 = new Thread(Joy2Start);
        th1.IsBackground = true;
        th2.IsBackground = true;
    }

在我的Thread方法下面

  private void Joy1Start()
    {
        var directInput = new DirectInput();

        var joystick = new Joystick(directInput, joy1Guid);
        joystick.Properties.BufferSize = 128;
        joystick.Acquire();

        while (q)
        {
            joystick.Poll();

            var state = joystick.GetCurrentState();
            var counter = 0;
            foreach (bool isPressed in state.Buttons)
            {
                if (isPressed)
                {
                    Action a1 = () => textBox1.Text = "JOY1";
                    textBox1.Invoke(a1);
                    th1.Abort();
                    th2.Abort();
                    q = false;
                    break;
                }
                counter++;
            }

        }

    }
    private void Joy2Start()
    {

        var directInput = new DirectInput();

        var joystick = new Joystick(directInput, joy2Guid);
        joystick.Properties.BufferSize = 128;
        joystick.Acquire(); 
        while (q)
        {
            joystick.Poll();

            var state = joystick.GetCurrentState();
            var counter = 0;
            foreach (bool isPressed in state.Buttons)
            {
                if (isPressed)
                {
                    Action a2 = () => textBox1.Text = "JOY2";
                    textBox1.Invoke(a2);
                    th1.Abort(); 
                    q = false;
                    break;
                }
                counter++;
            }

        } 
    }

我用按钮

开始启动线程
private void button1_Click(object sender, EventArgs e)
    {
        th1.Start();
        th2.Start();

    }

所以问题是如果我使用两个线程,我无法得到任何响应。

当我只开始th1或th2时,它就像一个魅力。

你能否告诉我这个算法的错误部分在哪里?

0 个答案:

没有答案