在CANBus适配器的隐藏代码中终止线程

时间:2012-07-23 21:00:13

标签: c# multithreading terminate abort

我正在使用CANBus adapter,当前正在Microsoft Visual C#2010 Express中为其编写代码。我正在尝试制作一个运行单独线程的GUI,用于通过CANBus串行适配器读取来自TEKTRONIX 020-2924-XX DPO DEMO 2板的消息。

我试图找出终止线程的安全方法(称为setReceiveCallBackThread)。但是,这个特殊的线程是特殊的,因为线程的代码不可用。它是CANBus API的一部分。

我在网上搜索(特别是堆栈溢出)关于如何安全地停止线程。我发现使用abort方法应该永远是最后的手段。

因此,如果我决定不能在线程上使用abort,我将不得不在canplus_setReceiveCallBack子例程中使用异常处理。但问题是我无法访问canplus_setReceiveCallBack;代码是隐藏的。请记住,这是一种独特的情况,因为我无法访问代码。与可以看到回调函数代码的所有其他情况不同,此子例程中的代码无法看到。

下面的代码应该是分析问题所需的一切,并希望在线程上提供使用Abort()的替代方法。

// CANSnifferForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;

namespace WindowsFormsApplication1
{


    public partial class CANSnifferForm : Form
    {

        // per the api document. "This is a blocking call and must be called on a separate thread."
        // the code previously after setCallback... was never being reached because the call is blocking.
        // this calls the setCallbackThread function in another thread so processing can continue.
        Thread setReceiveCallBackThread;
        bool stop;

        int can; // Return value of canplus_open

        uint idFilter; // Filter values entered by user
        ulong lenFilter; 
        bool stopThread; // Used for stopping thread         

        public CANSnifferForm()
        {
            InitializeComponent();
             del = new EASYSYNC.CallbackDelegate(callback);
        }


        private void callback(ref EASYSYNC.CANMsg msg)
        {
            // Populate the dataGridView
            if(InvokeRequired)
               BeginInvoke(del, msg);
            else
               this.dataGridView1.Rows.Add(msg.id, msg.len, msg.data, msg.timestamp);
        }

        private EASYSYNC.CallbackDelegate del;

        private void StartRestart_Click(object sender, EventArgs e)
        {
            this.CANSnifferStatusBox.Clear();
            this.CANSnifferStatusBox.AppendText("CAN closed");
            this.ProcessStatusBox.Clear();
            this.ProcessStatusBox.AppendText("Stopped");
            EASYSYNC.CANMsg msg = new EASYSYNC.CANMsg();
            msg.id = 1;
            msg.timestamp = 2;
            msg.flags = 3;
            msg.len = 4;
            msg.data = 5;

            // Attempt to open CANBus adapter
            can = EASYSYNC.canplus_Open(IntPtr.Zero, "1000", IntPtr.Zero, IntPtr.Zero, 0);

            if (can < 0)
            {
                // CANBus Adapter not opened
                this.ErrorBox.Clear();
                this.ErrorBox.AppendText("Error opening CAN");
                return;
            }

            // CANBus Adapter successfully opened
            this.CANSnifferStatusBox.Clear();
            this.CANSnifferStatusBox.AppendText("CAN open");

            // Initialize thread
            setReceiveCallBackThread = new Thread(() => EASYSYNC.canplus_setReceiveCallBack(can, del));

            // Attempt for CANBus adapter to listen
            if (EASYSYNC.canplus_Listen(can) < 0)
            {
                // CANBus Adapter not listening
                this.ErrorBox.Clear();
                this.ErrorBox.AppendText("Error setting listen mode\n");
                EASYSYNC.canplus_Close(can);
                this.CANSnifferStatusBox.Clear();
                this.CANSnifferStatusBox.AppendText("CAN closed");
                return;
            }

            // CANBus Adapter successfully listening
            this.CANSnifferStatusBox.Clear();
            this.CANSnifferStatusBox.AppendText("CAN Listening\n");

            // Place thread in background. Then start it
            setReceiveCallBackThread.IsBackground = true; 
            setReceiveCallBackThread.Start(); 
            while(!setReceiveCallBackThread.IsAlive);

            this.ProcessStatusBox.Clear();
            this.ProcessStatusBox.AppendText("Running\n");       


        }

        private void FilterData_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void Stop_Click(object sender, EventArgs e)
        {
           setReceiveCallBackThread.Abort(); // Stop thread
           while (setReceiveCallBackThread.IsAlive == true)
           {

           }

           this.ProcessStatusBox.Clear();
           this.ProcessStatusBox.AppendText("Stopped");


           // Attempt to flush CANBus Adapter
           if (EASYSYNC.canplus_Flush(can) < 0)
           {
               // CANBus not flushing
               this.ErrorBox.Clear();
               this.ErrorBox.AppendText("Error flushing CAN");
               EASYSYNC.canplus_Close(can); // Close CANBus Adapter
               this.CANSnifferStatusBox.Clear();
               this.CANSnifferStatusBox.AppendText("CAN closed");
               return;
           }
            // Attempt to reset CANBus Adapter
           if (EASYSYNC.canplus_Reset(can) < 0)
           {
               // CANBus not resetting
               this.ErrorBox.Clear();
               this.ErrorBox.AppendText("Error resetting CAN");
               EASYSYNC.canplus_Close(can); // Close CANBus Adapter
               this.CANSnifferStatusBox.Clear();
               this.CANSnifferStatusBox.AppendText("CAN closed");
               return;
           }

           this.CANSnifferStatusBox.Clear();
           this.CANSnifferStatusBox.AppendText("CAN closed");
           this.ErrorBox.Clear();
        }

        private void FilterID_KeyDown(object sender, EventArgs e)
        {

        }

        private void FilterLength_KeyDown(object sender, EventArgs e)
        {

        }


        private void FilterID_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
        {
            if (FilterIDBox.MaskFull)
            {

            }
            else if (e.Position == FilterIDBox.Mask.Length)
            {

            }
            else
            {

            }
        }

        private void FilterLength_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
        {
            if (FilterLengthBox.MaskFull)
            {

            }
            else if (e.Position == FilterLengthBox.Mask.Length)
            {

            }
            else
            {

            }

        }
    }
}

1 个答案:

答案 0 :(得分:0)

我的原始答案不正确。根据API指南

  

定义一个将在所有传入上接收回调的函数   消息。这是一个阻塞调用,必须单独调用   线。要取消注册此回调函数,   可以使用等于NULL的cbfn调用canplus_setReceiveCallback。

该文档没有说明被阻止的呼叫何时会退出,所以我的猜测是当你用NULL调用canplus_setReceiveCallback时它会退出。

我没有办法轻松测试它,但您可以通过在原始调用返回时输出文本来验证这一点。

setReceiveCallBackThread = new Thread(() => { EASYSYNC.canplus_setReceiveCallBack(can, del); Trace.WriteLine("EASYSYNC thread terminated"); });

您的Stop_Click方法可以使用以下命令停止该线程:

EASYSYNC.canplus_setReceiveCallBack(can, null);