473,785 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I clean up a long-running task before the process ends?

I have some classes that control file processing in c#. The files come
from a mainframe and may take some time for each to process. I use the
Threadpool to process multiple files at once. Each instance of the
file processor is spawned in its own AppDomain to isolate it (I'm using
a separate AppDomain for a valid reason, so this thread isn't to
discuss that). My process is a Windows service, but I can duplicate
this problem as a regular console project.

When the process is terminated (or the Windows service stopped), any
files currently processing are stopped midway even though there is code
in my finally block. I've included the relavent classes below:
The main executable has these methods:
static void Main(string[] args) {
// call test method here.
RunController() ;
Console.WriteLi ne("hit enter to exit");
Console.ReadLin e();
}
static void RunController() {
Controller ctrl = new Controller();
ctrl.DoWork();
}

And then the Controller class:

using System;
using System.Diagnost ics;
using System.Reflecti on;
using System.Threadin g;

namespace ConsoleTestHarn ess
{
public class Controller
{
public Controller(){
// Just so we can see the activity.
Trace.Listeners .Add(new TextWriterTrace Listener(Consol e.Out));
}
public void DoWork(){
// Three might be running at the same time.
for(int i = 0; i < 3; i++){
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Ex ecute));
}
}
private void Execute(object state){
AppDomainSetup setup = null;
AppDomain domain = null;

try{
setup = new AppDomainSetup( );
setup.Applicati onBase = AppDomain.Curre ntDomain.BaseDi rectory;

domain = AppDomain.Creat eDomain("Proces sor", null, setup);

Processor proc =
(Processor)doma in.CreateInstan ceAndUnwrap(Ass embly.GetExecut ingAssembly().F ullName,
typeof(Processo r).FullName);
proc.Process();
}finally{
if(domain != null)
AppDomain.Unloa d(domain);
}
}
}
}

And the processor class:

using System;
using System.Diagnost ics;

namespace ConsoleTestHarn ess
{
[Serializable()]
public class Processor
{
public void Process(){
try{
Trace.WriteLine ("Beginning Processing", this.ToString() );
// Simulate a long-running process.
System.Threadin g.Thread.Curren tThread.Suspend ();
}finally{
Trace.WriteLine ("Finished", this.ToString() );
// Close out database record an other cleanup.
}
}
}
}

I've stripped away irrelevant code. The code in the finally blocks
doesn't run, so files are left half-processed.

Has anyone else out there tackled a problem like this? Stopping a
service or terminating an EXE gracefully?
Best regards,
Jeffrey Palermo
http://www.jeffreypalermo.com

Nov 16 '05 #1
2 2443
For a service you might be able to override the OnStop method. But it is
difficult to hook the system when a process if simply forced to terminate.

You might want to cleanup when the process starts rather then when it is
terminated. You can still do normal housecleaning upon normal termination,
but also cleanup when starting since you do not know how it was terminated.

"Jeffrey Palermo, MCAD.Net" <je************ @gmail.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
I have some classes that control file processing in c#. The files come
from a mainframe and may take some time for each to process. I use the
Threadpool to process multiple files at once. Each instance of the
file processor is spawned in its own AppDomain to isolate it (I'm using
a separate AppDomain for a valid reason, so this thread isn't to
discuss that). My process is a Windows service, but I can duplicate
this problem as a regular console project.

When the process is terminated (or the Windows service stopped), any
files currently processing are stopped midway even though there is code
in my finally block. I've included the relavent classes below:
The main executable has these methods:
static void Main(string[] args) {
// call test method here.
RunController() ;
Console.WriteLi ne("hit enter to exit");
Console.ReadLin e();
}
static void RunController() {
Controller ctrl = new Controller();
ctrl.DoWork();
}

And then the Controller class:

using System;
using System.Diagnost ics;
using System.Reflecti on;
using System.Threadin g;

namespace ConsoleTestHarn ess
{
public class Controller
{
public Controller(){
// Just so we can see the activity.
Trace.Listeners .Add(new TextWriterTrace Listener(Consol e.Out));
}
public void DoWork(){
// Three might be running at the same time.
for(int i = 0; i < 3; i++){
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Ex ecute));
}
}
private void Execute(object state){
AppDomainSetup setup = null;
AppDomain domain = null;

try{
setup = new AppDomainSetup( );
setup.Applicati onBase = AppDomain.Curre ntDomain.BaseDi rectory;

domain = AppDomain.Creat eDomain("Proces sor", null, setup);

Processor proc =
(Processor)doma in.CreateInstan ceAndUnwrap(Ass embly.GetExecut ingAssembly().F u
llName, typeof(Processo r).FullName);
proc.Process();
}finally{
if(domain != null)
AppDomain.Unloa d(domain);
}
}
}
}

And the processor class:

using System;
using System.Diagnost ics;

namespace ConsoleTestHarn ess
{
[Serializable()]
public class Processor
{
public void Process(){
try{
Trace.WriteLine ("Beginning Processing", this.ToString() );
// Simulate a long-running process.
System.Threadin g.Thread.Curren tThread.Suspend ();
}finally{
Trace.WriteLine ("Finished", this.ToString() );
// Close out database record an other cleanup.
}
}
}
}

I've stripped away irrelevant code. The code in the finally blocks
doesn't run, so files are left half-processed.

Has anyone else out there tackled a problem like this? Stopping a
service or terminating an EXE gracefully?
Best regards,
Jeffrey Palermo
http://www.jeffreypalermo.com

Nov 16 '05 #2
I'll post my solution to this problem so that anyone searching this
thread isn't left hanging.

I send work to the Threadpool, so when the Threadpool executes my
method, I add that thread to an ArrayList and remove it when finished.
That way I have a list of current threadpool thread I'm using. When I
need to abort, I just loop through them all and call Abort() and Join()
on each thread. It sends a ThreadAbortExce ption down the thread, and
my normal cleanup code can execute. Join() blocks and waits until that
thread has exited before returning, so I delay the shutting down of my
service until all worker threads have exited. In this way, nothing is
left hanging. Here is my Controller class.

public class Controller
{
public ArrayList threads = new ArrayList();

public Controller(){
// Just so we can see the activity.
Trace.Listeners .Add(new TextWriterTrace Listener(Consol e.Out));
}
public void DoWork(){
try{
// Three might be running at the same time.
for(int i = 0; i < 3; i++){
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(Ex ecute));
}
Thread.Sleep(20 000);
Trace.WriteLine (threads.Count, this.ToString() );
}finally{
foreach(Thread t in threads){
t.Abort();
t.Join();
}
}
}
private void Execute(object state){
threads.Add(Thr ead.CurrentThre ad);

AppDomainSetup setup = null;
AppDomain domain = null;

try{
setup = new AppDomainSetup( );
setup.Applicati onBase = AppDomain.Curre ntDomain.BaseDi rectory;

domain = AppDomain.Creat eDomain("Proces sor", null, setup);

Processor proc =
(Processor)doma in.CreateInstan ceAndUnwrap(Ass embly.GetExecut ingAssembly().F ullName,
typeof(Processo r).FullName);
proc.Process();
}finally{
threads.Remove( Thread.CurrentT hread);
if(domain != null)
AppDomain.Unloa d(domain);
}
}
}

Best regards,
Jeffrey Palermo
Blog: http://www.jeffreypalermo.com

Nov 16 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5101
by: Jason | last post by:
I have a number of arrays that are populated with database values. I need to determine which array has the highest ubound out of all the arrays. The array size will always change based on the database record. Therefore, I need to be able to throw the arrays into a function that will automatically determine the highest ubound array. I was wondering if anyone might have a clean function that can do this. I have created a function that...
1
1879
by: Matt Garman | last post by:
I've got some code that generates a report for the user. The report is shown with explanatory verbage. The text is relatively long, and also has some simple formatting (paragraphs, bulleted lists). Right now the code is trivial, similar to the following: if (5 == result) { cout << "A value of five was returned because ...\n" << "\t- reason 1\n" << "\t- reason 2\n ...";
17
1833
by: Christopher Benson-Manica | last post by:
Yesterday I changed some code to use std::vectors and std::strings instead of character arrays. My boss asked me today why I did it, and I said that the code looks cleaner this way. He countered by saying that he was regarded the dyanamic allocation that C++ STL classes perform as being very inefficient. He also said that he wasn't particularly interested in clean code (!). My question to the group: In what situations, if any, would...
3
8631
by: kayjean | last post by:
Hi. I have a small test.cc >> g++ -o test test.cc (gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)) >> phase 1 (VSZ RSS 50844 47748 ) >> phase 2 (VSZ RSS 50844 47748 ) >> phase 3 (VSZ RSS 44696 41888 ) I found that vector.clear() doesn't free the memory. How to free the memory I used ??
7
2247
by: Felix Kater | last post by:
Hi, when I need to execute a general clean-up procedure (inside of a function) just before the function returns -- how do I do that when there are several returns spread over the whole function? My first approach: Use "while(1)" and "break", however this doesn't work if there is another loop inside (since I can't break two loops at the same time):
4
1912
by: Jeeran | last post by:
We use an ISAPI filter to convert long urls into short clean ones. For example: "Site.com/user/john/" Is re-written as: "Site.com/user/userinfo.aspx?uid=john" Now, "userinfo.aspx" contains a web user control which uses some Atlas functionality; The web user control contains a "DataList" which gets updated asynchronously through Atlas when the user clicks a button –the button is the Atlas trigger.
1
2599
by: Michael | last post by:
I have a solution for this, but it feels wrong. If anyone could offer a better one, I'm all ears. (Or technically, eyes.) Basically, I have a bunch of classes. For concreteness, one is a Matrix class, but that's only one example, so please don't get too hung up on it. I need to output and input these classes. I'd like a nice, pretty, human readable output, something like: 1 2 3
7
12908
by: siggi | last post by:
Hi all, when I do >>>sys.path in IDLE (winXP), i get a horrendously long list of paths, paths I may have used during a lot of trials and errors. How can I clean up sys.path? I mean, trim it of unnecessary paths? So far, I know only the command >>>sys.path.append(r'c:....etc...'), but how to delete or insert at the beginning of the list, I know not. Thanks,
232
13349
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *$ If the...
1
2166
by: sarahbanker | last post by:
ok, so I've inherited a nightmare of an Access 03 database, and trying to clean up the admin and maintainence side of it. It's being used as a tool to provide revised credit card limits based on gross income and UMI (uncommitted monthly income). I've tried various ways, but keep coming unstuck, so any help would be appreciated. Scenerio: Table Client Fields Client No UMI Gross Income ...
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9484
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10157
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10097
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8983
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7505
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.