如何在C#中杀死线程 [英] how to kill a thread in C#

查看:1012
本文介绍了如何在C#中杀死线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(对不起,我的英文不好)我在程序中创建了一个线程以使用api,它在C ++库中.该api将接受来自COM端口的输入消息,这可能是一个循环代码.必须等待其超时,然后它将返回信息.现在,我必须终止线程以退出来自COM端口的输入消息.我已经使用Thread.Abort函数来停止线程,但无法正常工作.我该如何使我认为也许我必须使用非托管方法创建一个线程,然后才能杀死它.

(Sorry,my English is poor)I created a thread in my program to use an api.It is in a C++ library.This api is about to accept input messages from COM port.It is maybe a loop code.I have to wait for its timeout and then it will return information.Now I have to kill the thread to quit input messages from COM port.I''ve used Thread.Abort function to stop the thread,but not work.How can I make it?I think maybe I have to create a thread using unmanaged method and then I can kill it.

推荐答案

尝试t.Interrupt();,然后t.Abort();

或:
try t.Interrupt(); and then t.Abort();

Or:
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;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Boolean run = true;
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(trun));
            t.Start();
        }
        public void trun()
        {
            while (run == true)
            {
                MessageBox.Show("dfg");//doing something 
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            run = false;//change value to abort function(and thread(tested(see in Task Manager));
        }
    }
}


这篇关于如何在C#中杀死线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆