I have a console application, in which I have a connection to a third party windows service on a remote server by tcp/ip.
The call Hierarchy likes:
static class Program
{
[MTAThread]
static void Main()
{
MyApplication.Start();
The Start
method
public static void Start()
{
lock (SyncVar)
{
ThreadStart ts = new ThreadStart(MainCode);
MainCodeThread = new Thread(ts);
MainCodeThread.IsBackground = false;
MainCodeThread.Start();
The detail of main thread has:
private static void MainCode()
{
try
{
// connect to the remote server, against a windows service
TelephonyServer tServer = new TelephonyServer(sIpaddress, "username", "password");
while (true)
{
Task consumer = Task.Run(() =>
{
if (data != "")
{
ProcessEachChannel(data);
});
Task producer = Task.Run(() =>
{
// blah blah
});
In the method ProcessEachChannel
, we have
public bool ProcessEachChannel(string workItem)
{
ChannelResource cr = tServer.GetChannel();
// blah blah
}
Now the application is working well. However if I click the red exit cross of the application or click stop debugging button from Visual Studio, the resources ChannelResource cr
is not destroyed at all. I found the fact from the remote server service control dashboard.
I tried some code
System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
process.Exited += new EventHandler(OnExited);
It is not helpful. I heard some tricks to manage the thread by passing parameters to the main thread then set something true
or false
etc but just no clue.