473,395 Members | 1,948 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

threading problem; dot net bug or me? (test case included)

I've written a small windows service, and I'm having a problem that I'm
spending a lot more time on than I'd like.
If anyone has experienced this problem and has any hints or solutions; they
would be appreciated.

Simply leaving the threadMain() method if something unexpected occurs during
thread execution leaves the thread in a ThreadState.Running state. This
(apparently??) causes the Thread.Join() in service.OnStop() to hang
indefinitely, resulting in a service that can't be stopped. A
Thread.Sleep(0) in threadMain() yields the same result. So I thought I'd ask
the service to stop from the thread and then just hang around, waiting for a
regular service shutdown. ServiceController.Stop() does seem to run
asynchronously, so no obvious problems to this, except that it always hangs
on the instruction setting the field ThreadCodeClass.dieNow.

As for dieNow, I've tried using a lock(this) section in a property instead
of the volatile field. Didn't work either.
Tried compiling against v1.0.3705 and v1.1.4322, same result.

===== Source code =====
using System;
using System.IO;
using System.ServiceProcess;
using System.Threading;

namespace Dummy {

public class Debug {
private static StreamWriter sw;

public static void log(string s) {
if (sw == null) {
sw = File.AppendText("c:\\lagkage.txt");
sw.AutoFlush = true;
sw.Write("\r\n\r\n--- Test run at " + DateTime.Now + " ---\r\n\r\n");
}
// no thread safety information in the .net docs on System.IO.File;
locking just to be sure
lock(sw) {
sw.Write("" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff "));
sw.WriteLine(s);
}
}
}

public class ThreadCodeClass {
public volatile bool dieNow = false;

public void threadMain() {
Debug.log("Thread: started.");
try {
while (! dieNow) {
Debug.log("Thread: running.");
// code that does one thing or the other would be here
throw new Exception("wak wak simulated failure");
Thread.Sleep(5000);
}
} catch (Exception e) {
Debug.log("Thread: Unexpected exception occured; I don't know how to
handle this. This is fatal; attempting automated service shutdown. Exception
was: " + e.Message);
try {
ServiceController sc = new ServiceController(TestService.serviceName);
// Assuming this is done asynchronously - the .net docs doesn't mention
sc.Stop();
Debug.log("Thread: Service stop initiated.");
} catch { }
}
while (! dieNow) {
Debug.log("Thread: Waiting for termination request. dieNow is " +
dieNow + ", sleeping.");
Thread.Sleep(5000);
}
Debug.log("Thread: Dying.");
}
}

public class TestService : System.ServiceProcess.ServiceBase {
public const string serviceName = "TestService";
private Thread wT = null;
private ThreadCodeClass wT2 = null;

public TestService() {
ServiceName = serviceName;
}

static void Main() {
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new
TestService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRu n);
}

protected override void OnStart(string[] args) {
Debug.log("Service: Starting service.");
ThreadCodeClass wT2 = new ThreadCodeClass();
wT = new Thread(new ThreadStart(wT2.threadMain));
wT.Start();
Debug.log("Service: Service started.");
}

protected override void OnStop() {
Debug.log("Service: Stop signal received. Stopping and joining thread
(thread state is: " + wT.ThreadState + ")");//, dieNow is " + wT2.dieNow +
")...");
// Now why doesn't this work:
wT2.dieNow = true;
Debug.log("Service: Volatile dieNow set to true. Reading dieNow yields: "
+ wT2.dieNow + ". Joining thread...");
wT.Join();
Debug.log("Service: Service stopped.");
}
}
}

===== End source code =====

Copy-paste into a windows service project, compile and install as service.
Upon starting the service, it should generate a log file, which should
contain something like this:

===== Log file =====
Service: Starting service.
Service: Service started.
Thread: started.
Thread: running.
Thread: Unexpected exception occured; I don't know how to handle this. This
is fatal; attempting automated service shutdown. Exception was: wak wak
simulated failure
Service: Stop signal received. Stopping and joining thread (thread state is:
Running)
Thread: Service stop initiated.
Thread: Waiting for termination request. dieNow is False, sleeping.
===== End log file =====

The "Service: Stop signal received" doesn't always occur, atm. I believe
it's a thread context switch issue, but that this isn't the real problem.
Run the service again (kill it with "kill testservice" first) if it fails to
produce this line :-)...
On this system, the line is produced almost every time.

Ciao!
Jul 21 '05 #1
0 3472

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

Similar topics

5
by: Garry Hodgson | last post by:
a colleague of mine has seen an odd problem in some code of ours. we initially noticed it on webware, but in distilling a test case it seems to be strictly a python issue. in the real system, it...
0
by: James R. Saker Jr. | last post by:
I've got a: "start server thread > Queue object, start server thread <> Queue object, start parsing client < Queue object" application that's got me puzzled. Probably an easy threads issue, but...
77
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for...
6
by: WindAndWaves | last post by:
Hi Folks I have inhereted a script that I understand reasonably well, I just do not understand !/^\d+$/.test(el.value) what the hell does that mean? Below is the script (there are really...
8
by: MattB | last post by:
Hello I am starting a new thread in a button click event. This thread calls an method which sends emails, I don't want the page to wait for the emails to finish going out as it slows the user...
0
by: David | last post by:
I've written a small windows service, and I'm having a problem that I'm spending a lot more time on than I'd like. If anyone has experienced this problem and has any hints or solutions; they would...
28
by: robert | last post by:
In very rare cases a program crashes (hard to reproduce) : * several threads work on an object tree with dict's etc. in it. Items are added, deleted, iteration over .keys() ... ). The threads are...
17
by: OlafMeding | last post by:
Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. ...
2
by: Panard | last post by:
Hi, I'm experiencing a strange problem while trying to manage a ftp connection into a separate thread. I'm on linux, python 2.4.3 Here is a test : ------ ftp_thread.py ------ import ftplib...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.