ThreadStart delegate does not execute until Console.Readline() is provided - c#

I have some problem with ThreadStart delegate. After I provide a function and start the thread nothing is actually happening. I need to add Console.Readline() to write messages to a file. Why it behaves like that?
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStart
{
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(new System.Threading.ThreadStart(() =>
{
int messageSeq = 0;
while (messageSeq < 5)
{
File.AppendAllText(#"c:\Test\write.txt", DateTime.Now.ToString() + Environment.NewLine);
messageSeq++;
Thread.Sleep(TimeSpan.FromMinutes(1));
}
}));
thread.IsBackground = true;
thread.Start();
//Console.ReadLine();
}
}
}
I don't have experience in multi-threaded applications so i might be missing something simple

Thread.IsBackground Property
A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating.
You're telling the thread not to force the application to stay running, and then you're letting the application close by returning from the Main method.
Console.ReadLine(); will stop the application returning from Main and will give the thread time to do it's work.
Thread.Start Method
Note that the call to Start does not block the calling thread.
The Start method of the Thread doesn't block the calling thread. That means it returns ~right away and the calling thread continues to execute.
Console.ReadLine Method
If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key.
Console.ReadLine() does block the calling thread until the user hits enter/return in the console (causing a new line).

Related

How to handle exception in using(Py.GIL()) block pythonnet

Is there a way to handle exceptions in using the (Py.GIL()) block?
For example:
using System;
using Python.Runtime;
public class Test{
public static void Main(){
using(Py.GIL()){
try{
dynamic module = Py.Import("module");
dynamic result = module.function("argument");
Console.WriteLine(result);
}
catch(Excepiton ex){
// Handled Exception
}
}
}
}
I asked this question because I call a C# function which uses the using(Py.GIL()) block. It is executed with a new thread which the Main thread waits for to finish.
It works for the first round, but for the next, it stops on the using block, and the application freezes without showing any exception.
I even tried to stop the Main thread from waiting for the execution, but the worker thread still stops at the using block of Py.GIL() after the first round.
For the thread execution, I am using the Thread pool.
Thread.Factory.StartNew(FunctionName);
This issue was caused by the way Python handles threads. The main thread must start the Python engine and enable threading.
PythonEngine.Initialize();
PythonEngine.BeginAllowThreads();
Run the above code on the Main thread before using worker thread that uses using(Py.GIL()) block.

Why does the main thread's output come first in C#?

I wrote this little program:
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(WriteX);
t.Start();
for (int i = 0; i < 1000; i++)
{
Console.Write("O");
}
}
private static void WriteX()
{
for (int i = 0; i < 1000; i++)
{
Console.Write(".");
}
}
}
I ran it about fifty times, and the first character on the console was always "O". It is weird for me, because the t thread starts first then the main continues.
Is there any explanation for this?
This is probably because Thread.Start first causes the change of state of thread on which it is called and OS schedules it for execution whereas the main thread is already running and does not need these two steps. This is probably the reason that the statement in main thread executes first rather the one in the newly created thread. Keep in mind the sequence of thread execution is not guaranteed.
Thread.Start Method
1) Thread.Start Method Causes the operating system to change the state of
the current instance to ThreadState.Running.
2) Once a thread is in the ThreadState.Running state, the operating
system can schedule it for execution. The thread begins executing at
the first line of the method represented by the ThreadStart
Edit It seems to me that representing this in graphical form will make this more clear and understandable. I tried to show the sequence of thread execution in diagram below.
You say:
"It is weird for me, because the t thread starts first then the main continues.".
This is not true. The "main" tread is already running. When t.Start(); is executed, the OS is told t is in the running state. The OS will then schedule execution time for the thread "soon". This is something else than the OS is instructed to stop execution of this thread until thread t is started. In other words, when Start returns, there is no guarantee that the thread has already started executing.
More of an advice than not an answer:
(Please note, that I see no real-life use for what you are trying to achieve, so I treat your problem as a thought experiment/proof of a concept not explained in detail.)
If you want your threads to "race" for control, don't give your main thread a head start! Creating a thread has some overhead and your main thread is already created (since it creates your other thread). If you are looking for a mostly equal chance for both of your main and worker thread, you should wait for your worker thread to be created in the main thread and wait for the main thread to start the race in your background thread. This can be achived by synch objects.
In practice it would look like this:
You should declare two ManualResetEvents which are visible for both your main- and background thread like this:
private static ManualResetEvent backgroundThreadReady = new ManualResetEvent(false);
private static ManualResetEvent startThreadRace = new ManualResetEvent(false);
Then in your main thread, you should wait for your thread being initialized like:
static void Main(string[] args)
{
Thread t = new Thread(WriteX);
t.Start();
backgroundThreadReady.WaitOne(); // wait for background thread to be ready
startThreadRace.Set(); // signal your background thread to start the race
for (int i = 0; i < 1000; i++)
{
Console.Write("O");
}
}
And in your thread:
private static void WriteX()
{
backgroundThreadReady.Set(); // inform your main thread that this thread is ready for the race
startThreadRace.WaitOne(); // wait 'till the main thread starts the race
for (int i = 0; i < 1000; i++)
{
Console.Write(".");
}
}
Please note that I could have used other waitable sync objects (mutex, autoreset event, even a critical section lock with some hack, I've just choose the simplest, fastest solution which can be extended easily).
Your code is non deterministic. Your code contains no thread primitives that would schedule priority of one thread over another or for one thread to wait for another.
Main process continue its next instructions set after invoking the thread ,It will take time to start thread method as light process.
It basically needs time to start the thread up. You are running the thread code at the same time as the rest of the first method. So taking into account the time it takes to start the thread and then get to the point where it is writing the "." does that make sense?
If you have a sort of reset button in your app to start everything again (without exiting) you may find that the first character is the "." because the thread will already exist.
There is only one reason why the main thread will finish before the created thread and that is because it takes time to start a thread. The only time you would use threads to speed up a program is when 2 tasks can be run at the exact same time. If you want to make the second loop finish first , take a look at Parallel.For loops in c#... these will run each loop in the for loop at the same time (not all of them but as much as your PC can handle)

Can this cause deadlock? BeginInvoke() & thread.Join()

I have this code that many threads can call to update the GUI:
MethodInvoker del = () => { lblInfo.Text = tmp; };
lblInfo.BeginInvoke(del);
(lblInfo is created by the GUI thread)
I also have this method called at button click executed by the GUI thread:
public void Stop()
{
isStopping = true;
crawler.Join();
foreach (Thread t in txtWorkers)
{
t.Join();
}
indexer.Join();
lblStatus.Text = "Stopped";
lblInfo.Text = "";
}
1 time over 100 run the program deadlock at Stop button click. I was not debugging when i saw the deadlock so i can't be sure about the state of the various threads but i'm almost sure that all the threads i'm joining will eventually reach the point where they check for
isStopping value and terminate. This leads me to think that there may be a problem with the BeginInvoke but can't really find it. It should be async so threads calling it (crawler & indexer) should not block. What happens if the GUI thread is executing Stop() and also must execute a call from BeginInvoke? Could this be the problem? Is there something i can't see about the thread i'm joining?
EDIT:
What the code looks like after the suggested changes:
public void Stop()
{
/*
...disable GUI
*/
isStopping = true; // Declared as volatile
lblStatus.Text = "Stopping...";
// Creating a thread that will wait for other threads to terminate
Task.Factory.StartNew(() =>
{
crawler.Join();
foreach (Thread t in txtWorkers)
{
t.Join();
}
indexer.Join();
// Adjust UI now that all threads are terminated
MethodInvoker del = () =>
{
/*
...enable GUI
*/
lblStatus.Text = "Not Running";
isStopping = false;
};
lblStatus.BeginInvoke(del);
});
}
It seems to be working, i hope that deadlock is gone...
I don't think it should be a problem, because you're using BeginInvoke rather than Invoke - the background threads will just proceed past that line without waiting for the GUI to catch up. If you're using Control.Invoke anywhere, that could cause a deadlock.
More importantly, using Join in your GUI thread is fundamentally a bad idea - the UI will be frozen until everything's finished. It would be better to disable any controls which could start anything new, set your isStopping flag, and then create a new thread to wait for all the threads to stop - and when all the threads have finished, then update the UI with BeginInvoke again. (If you're using .NET 4.5 you could also use an asynchronous method for this, creating and awaiting a task to wait for all the threads.)
Finally, if isStopping is just a bool field, there's no guarantee that your background threads will "see" the change from the UI thread. It's possible that making the field volatile would fix this, but the precise meaning of volatile scares me. An alternative would be to use the Interlocked class, or make it a property which obtains a lock for both reading and writing - that ensures appropriate memory barriers are in place.

C# .Net 4.0 Console App - how to stay alive until all threads complete? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C#: Waiting for all threads to complete
I have a console app that spawns some threads and then exits. Each thread takes roughly ~20 seconds to complete. It appears as though the console app is spawning the threads and then exiting before the threads have a chance to complete.
How do I tell the console app not to exit until all threads it has spawned have completed?
You can to use a CountDownEvent.
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static CountdownEvent countdown;
static void Main(string[] args)
{
countdown = new CountdownEvent(1);
for (int i = 1; i < 5; i++)
{
countdown.AddCount(); //add a count for each (BEFORE starting thread .. Thanks, Brian!)
//do stuff to start background thread
}
countdown.Signal(); //subtract your initial count
countdown.Wait(); //wait until countdown reaches zero
//done!
}
static void backgroundwork()
{
//work
countdown.Signal(); //signal this thread's completion (subtract one from count)
}
}
}
Are the threads spawned for a loop? If so a Parallel.ForEach would work:
ParallelOptions options = new ParallelOptions();
Parallel.ForEach(items, options, item=>
{
// Do Work here
});
As long as the Thread is not a background-thread (.IsBackground), the app should stay alive:
static void Main()
{
Thread thread = new Thread(MoreStuff);
thread.IsBackground = false;
thread.Start();
Console.WriteLine("Main thread exiting");
}
static void MoreStuff()
{
Console.WriteLine("Second thread starting");
Thread.Sleep(5000); // simulate work
Console.WriteLine("Second thread exiting");
}
Nothing else is needed. Note that the ThreadPool will use background threads; is the problem perhaps that you are using ThreadPool here?
Note: if the second thread hasn't actually started there might be a small race where it can exit prematurely; you might want to gate the threads starting.
You can use Thread.Join to wait for a thread to complete.
How are you launching the threads? It really depends, but if you are just using the Thread class, then call yourThread[i].Join() from the main thread to ensure that all threads complete.
Look into the Tasks and Task Factory to handle things a lot more cleanly than in years past.
Call Thread.Join() on all of the Threads that you start after they have started. This will block the current thread until the thread is complete.
You should probably use synchronization and wait for any spawned threads to complete their work, either by blocking the main thread with calls to Thread.Join or using signalling (e.g. using a Monitor or one of the other options for this).
Alternatively you can simply make the spawned threads run as foreground threads, by setting the IsForeground property (afaicr). This will keep the application alive until the threads have terminated, but you will still see the console window disappear as the main thread exits.

Stopping work from one thread using another thread

Not sure if my title is worded well, but whatever :)
I have two threads: the main thread with the work that needs to be done, and a worker thread that contains a form with a progress bar and a cancel button. In normal code, it would be the other way around, but I can't do that in this case.
When the user clicks the cancel button, a prompt is displayed asking if he wants to really cancel the work. The problem is that work continues on the main thread. I can get the main thread to stop work and such, but I would like for it to stop doing work when he clicks "Yes" on the prompt.
Example:
// Main thread work starts here
t1 = new Thread(new ThreadStart(progressForm_Start));
t1.Start();
// Working
for (i = 0; i <= 10000; i++)
{
semaphore.WaitOne();
if (pBar.Running)
bgworker_ProgressChanged(i);
semaphore.Release();
if (pBar.IsCancelled) break;
}
t1.Abort();
// Main thread work ends here
// Start progress bar form in another thread
void progressForm_Start()
{
pBar.Status("Starting");
pBar.ShowDialog();
}
I could theoretically include a prompt in the cancelWatch() function, but then I would have to do that everywhere I'm implementing this class.
I have a couple of quick comments:
Avoid using Thread.Abort() here's why.
Make your thread a background thread: Thread.IsBackground = true (this will automatically exit the thread when your app exits).
Here is a detailed discussion on how to safely stop a thread from running: Is it safe to use a boolean flag to stop a thread from running in C#
To stop the work on the main thread you'd have to do something like this:
boolean volatile isRunning = true;
static void Main(...)
{
// ...
// Working
for (i = 0; i <= 10000; i++)
{
semaphore.WaitOne();
if (!isRunning) break; // exit if not running
if (pBar.Running)
bgworker_ProgressChanged(i);
semaphore.Release();
}
//...
t1.Interrupt();// make the worker thread catch the exception
}
//
void cancelButton_Click(object sender, EventArgs e)
{
isRunning = false; // optimistic stop
semaphore.Release();
}
I recommend using CancellationTokenSource, which can handle this kind of complex scenario. It's part of the Task Parallel Library but does not actually have to be used with Task objects; it can just as easily be used with old-style Thread objects.
Of course, if you have the time, I'd recommend defining the main thread's work as a Task object (running on the main UI thread by using TaskScheduler.FromCurrentSynchronizationContext).
Note that everything above assumes .NET 4.0. If you're still stuck on the old platform, you'll just have to have a bool cancelled; field protected by a lock or some such thing. Tip: don't call Thread.Abort; it's evil.

Categories

Resources