I am using thread to start a public function of a class. The problem is that only if set break point inside the thread function(public function of the class) it gets called otherwise calling the Thread.Start is not having any effect. Once the thread function is called it is completing successfully giving desired results.
QueueProcessor processor = null;
Thread subprocess =null;
public void processQueue()
{
if (processor == null)
{
processor = new QueueProcessor();
}
if (subprocess == null)
{
subprocess = new Thread(processor.run);
subprocess.IsBackground = true;
}
if (!subprocess.IsAlive)
{
subprocess.Start();
}
else
{
}
}
class QueueProcessor
{
public QueueProcessor()
{
instance = new RecordDao();
service = new CommonsService();
}
public void run()
{
startProcessing(); // it won't reach here unless a breakpoint is set.
}
public bool startProcessing()
{
//some database routines here.
// some web service calls here
}
}
Please help.
EDIT: Now that you’ve changed the code, there are two problems:
You potentially try to restart a thread, if you ever call
processQueueafter the processing has finished. You can’t do that.If
processQueueis called from multiple threads, you have issues of potentially starting multiple threads due to race conditions, and also memory model potential issues.The first point is more simply solved using:
… but this still leaves the potential problem of the second point. What is calling
processQueue? Is it always the same thread? (And why are you ignoring .NET naming conventions?)My guess is that what you’re seeing is actually the processing happening exactly once, but there being no work to do, and future calls not restarting the thread as presumably you expected – whereas if you have the breakpoint there, then by the time you hit “go” again, there’s work to do. At a guess… certainly starting a thread does work without breakpoints, so the flaw is somewhere in your code. If you could produce a short but complete program that demonstrates the problem, we could get to the bottom of it.
Your thread does almost nothing, so it’s entirely reasonable for the thread to complete before it reaches the
whileloop. It’s not that it doesn’t start – it’s that it starts and then finishes immediately.Alternatively, you could have an execution flow like this:
The thread has executed with no problems, but
IsAliveis always false.It’s not clear why you have this code in the first place – what are you trying to achieve?