Question : if I try to construct a heartbeat thread to monitor certain thread/process is alive, furthermore, if the such artifacts don’t exist any more, the host thread/process will be terminated accordingly.
My apporach : Task with CancellationToken and Timer controller, the code skeletion has been attached as follow.
Further informaiton could be found in Jerry, Richter’s version 3.0’s introdution, However, my approach isn’t so good. As there is no inner mechnaism for Timer object to receieve asynchronous/synchronus event.
To-Do Action : estabish a inner Timer ojbect, which could be controller via any relevant outer thread.
Discussion : How Reinhold think bout this affair?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//TODO : CancellationTokenSource
using System.Threading;
//TODO : Task
using System.Threading.Tasks;

namespace TaskCancelThread
{
class Program
{
///

///
///

private static int iDuration = 2000;

///

///
///

class StatusChecker
{
private System.Threading.Timer _controller;

public System.Threading.Timer Controller{
get
{
return this._controller;
}
set
{
System.Diagnostics.Debug.Assert(value != null);
this._controller = value;
}
}

///

///
///

private int _iProcessId;

public StatusChecker(int _iProId)
{
this._iProcessId = _iProId;
}

// This method is called by the timer delegate.
public void CheckProcessAlive(object timerObject)
{
CancellationTokenSource cts = timerObject as CancellationTokenSource;
System.Diagnostics.Debug.WriteLine("Task Status - " + cts.Token.CanBeCanceled);
if (!cts.Token.CanBeCanceled)
return;
cts.Cancel(true);
if (this._controller != null)
{
try
{
this._controller.Dispose();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
}
}
}

static int Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();

Task _test = new Task(() =>
{
//TODO : call long running thread
try
{
System.Threading.Thread.Sleep(6000);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(" **** " + ex + " **** ");
}
return 0;
}, cts.Token);

StatusChecker tcb = new StatusChecker(System.Diagnostics.Process.GetCurrentProcess().Id);
System.Threading.Timer stateTimer = new System.Threading.Timer(tcb.CheckProcessAlive, cts, iDuration, iDuration);
tcb.Controller = stateTimer;

_test.Start();

int nRet = -1;
try
{
//TODO : Waiting for Token termination
_test.Wait(cts.Token);
nRet = _test.Result;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
finally
{
stateTimer.Dispose();
}
System.Diagnostics.Debug.WriteLine("**** Thread Process Return Value - " + nRet + " ****");
return nRet;
}
}
}

Advertisements