Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
(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.
Posted

1 solution

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));
        }
    }
}
 
Share this answer
 
v3
Comments
Wei Shen 26-Sep-10 5:11am    
I's not work.Thread.ThreadState is AbortRequested until the function return.
Wei Shen 26-Sep-10 5:36am    
Thank you very much.
Maybe you don't understand my problem.I use an API with a thread(named temp) in C++ DLL.Improt code is:

[DllImport("YLCardApp.dll", CharSet = CharSet.Ansi)]
public static extern int YL_TransProcess(byte[] ulRequest, byte[] ulResponse);

I can't control this loop code.What can I do is to kill the thread temp and release resources.Now the problem is temp can't be stoped.

Thank you again.
Wei Shen 26-Sep-10 5:37am    
Reason for my vote of 5
Automatic vote of 5 for accepting answer.
[no name] 26-Sep-10 5:48am    
Can you post part of code for more understanding?
agent_kruger 16-Jan-14 6:55am    
in my case when i write interupt and then abort, it does not do anything but before finishing the code block it gives an error "Thread Aborted". I took the whole code block in try catch and didn't throw any error message but it still shows error message. So, any idea how to stop the Thread?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900