I was looking at the Microsoft MSDN reference page regarding the modifier "volatile", and was a little unsure as to the way in which the snippet they provided, waited for a thread to complete execution.
I know it is only example code, and that the thread completed very quickly, but I believe that the code below is not very good for developers trying to understand threading.
I believe Microsoft have actually presented a code snippet which will introduce a "tight-loop" in the code. Now I appreciate that it will not affect this code snippet (that much), but if a developer takes this code and tries to use it for some multi-threaded code that is a little more intensive, I would presume the "tight-loop" issue would arise?
using System;
using System.Threading;
class Test
{
public static int result;
public static volatile bool finished;
static void Thread2() {
result = 143;
finished = true;
}
static void Main() {
finished = false;
// Run Thread2() in a new thread
new Thread(new ThreadStart(Thread2)).Start();
// Wait for Thread2 to signal that it has a result by setting
// finished to true.
for (;;) {
if (finished) {
Console.WriteLine("result = {0}", result);
return;
}
}
}
}
Snippet reference:
http://msdn.microsoft.com/en-gb/library/aa645755(v=vs.71).aspx
What would be the better way to wait for the thread to finish, in the example above, which would not introduce this "tight-loop" situation?
Or, will a "tight-loop" not actually be introduced at all?
Please note, that the purpose of the snippet is to demonstrate the "volatile" keyword, so using a Thread.Join() would take the snippet out of context I believe.
This snippet doesn't illustrate how to wait, this just illustrates access to a volatile field from different threads.
To wait for your background thread simply, you can use this snippet:
AutoResetEvent autoEvent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem((o) =>
{
// do your stuff
((AutoResetEvent)o).Set();
}, autoEvent);
autoEvent.WaitOne();
As you say the best way to wait for a thread to finish would be to use Thread.Join or an ManualResetEventSlim event however neither of these would require a volatile bool.
It would be possible to use the code in the example by adding a call to Thread.SpinWait in the loop. This would help to prevent processor starvation. In version 4 of .Net Microsoft added a struct called SpinWait that can be used more effectivly.
There is more information about this in "Threading in C#" by Joseph Albahari
Related
I'm trying to learn threading on C# but have got a bit stuck on how to handle properties.
Take for example my class NavigateIE which can only carry out a single action at a time. I thought if I had a property busy then I would know if the instance was busy outside the class.
class NavigateIE
{
public bool busy;
public void IEAction(string action)
{
busy = true;
var th = new Thread(() =>
{
try
{
//Do stuff
}
catch(Exception ex)
{
//report Exception
}
finally
{
busy = false;
}
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
}
However, as busy = false; is only ever called inside the thread then this doesn't work as navigateIE.busy is always true.
class MainElsewhere
{
private NavigateIE navigateIE = new NavigateIE();
private void Main()
{
if (!navigateIE.busy)
{
//navigateIE.busy always == true
}
}
}
I have 2 questions:
1) How do I set up the property so it's threadsafe and busy = false; is seen outside the class?
2) Is there a better way to do this?
Edit: Essentially NavigateIE is a class to handle a single instance of IE using Watin. I can only call a method in NavigateIE if there are no other methods running otherwsie a previous action has not completed. NavigateIE is called from a main method that is on a timer tick, hence why I need to check if the class is busy.
navigateIE.busy == false the first time but after the thread sets it back to false the main method still sees navigateIE.busy == true.
You are doing this fundamentally wrong. Yes, busy is pretty likely to be true, that thread will start running quickly on a modern multi-core processor. No actual guarantee, it is merely very common. Exactly when it turns back to false is highly unpredictable as well, depends what the thread does. Including never, a bool is not a synchronization primitive.
It is not clear to me what you are trying to achieve, but you don't actually need to use a busy flag at all. IE is an apartment-threaded COM object, it already automatically marshals the call to the STA thread that owns the object. Calling its Navigate() method from another thread is fine, no extra code is required to help. If you need a busy flag to indicate that the browser is working on a command then you'll need a flag that you set to true when you actually start navigating instead of when you start the thread. Leverage the code in this answer, perhaps.
I started to write an answer, but there are just a lot of variables here. (you should be locking, but really signalling might be a better solution, etc). I really think that rather than throwing a code snippet at you, a better answer would be do direct you to do a little more digging on .net threading.
Here's an ebook that might be helpful for you: http://www.albahari.com/threading/
How do I set up the property so [..] busy = false; is seen outside the class?
Your example doesn't work because busy needs to be marked volatile
Is there a better way to do this?
It sounds like all calls within NavigateIE always need to be serialized. If that's true, I would just put a lock statement in each thread-call
public object mutex = new object();
public void IEAction(string action)
{
var th = new Thread(() =>
{
lock(mutex)
{
//Serialzed code goes here
}
});
//etc.
}
Also, note that you rarely want to actually create your own Thread instance - you should either be using a BackgroundWorker, obtaining a thread from the ThreadPool, or using the new Tasks Parallel Library (TPL).
If you're unsure, the TPL is usually the best place to start.
I would please like to know where I can get an example of multithreading or asynchronous threading.
In the application that I am busy with I have to run a thread in the background of my application to fetch a value that is changing. And whenever this value reaches a certain amount then it needs to call another function. All this has to run in the background of the program so that the user can still do something else on the application.
Any examples or links that could help would really be appreciated.
In order to summarize the options, I will try to list them here (maybe it would be a good idea to make this a community wiki).
First of all, you can simply start a function in another thread:
Thread t = new Thread( ThreadProc );
t.Start();
// now you can wait for thread to finish with t.Join() or just continue
// Thread.IsBackground allows to control how thread lifetime influences
// the lifetime of the application
...
static void ThreadProc() {...} // can also be non-static, but for simplicity....
Then you can use BackgroundWorker:
BackgroundWorker bgWorker = new BackgroundWorker();
bgWorker.DoWork += MyFunction;
bgWorker.RunWorkerAsync();
voud MyFunction(object o, DoWorkEventArgs args) {...}
You can use ProgressChanged and RunWorkerCompleted events for more control (as well as WorkerReportsProgress and other properties)
Another option is to use ThreadPool, if your method will not take too much time:
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
...
static void ThreadProc(Object stateInfo) { ... }
Yet another option is to call BeginInvoke on a delegate:
public delegate int MyDelegate(...);
MyDelegate del = SomeFunction;
IAsyncResult ar = del.BeginInvoke(...);
int result = del.EndInvoke(ar);
This will execute on a thread from the thread pool. If you need to wait on calling thread, you can use IAsyncResult.IsCompleted, but it will block the calling thread.
And of course, you can use Task:
var task = Task.Factory.StartNew(() => MyMethod());
This will also execute MyMethod on a thread from the thread pool, so the same warnings apply (although you can use TaskCreationOptions.LongRunning to ensure that the new thread is always created). Under some circumstances (when you wait on task) it can even execute on the same thread, but it is well optimized so you should not worry about that.
This is probably the option with best tradeoff of simplicity vs control (of course, there is no really 'the best'). Here are the benefits (shamelessly stolen from Jon Skeet's answer):
Adding continuations (Task.ContinueWith)
Waiting for multiple tasks to complete (either all or any)
Capturing errors in the task and interrogating them later
Capturing cancellation (and allowing you to specify cancellation to start with)
Potentially having a return value
Using await in C# 5
Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)
Well depending on the level of control that you seek a BackgroundWorker could easily work and its found within the System.ComponentModel.BackgroundWorker. Now here is a link to the MSDN docs on the subject matter : http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
a Simple usecase secenario is like so:
BackgrouWorker BG = new BackgroudWorker();
GB.DoWork += YourFunctionDelegate(object Sender, EventArgs e);
GB.RunWorkerAsync();
Now YourFunctionDelegate(object Sender,EventArgs e) should be what ever it is you want run in the background. However needs to follow this argument form, There are also a good amount of helper functions associated with the backgroundworker like onProgressChanged event that allows monitoring of obviously progress, which if you are new to threading can prove to be a pain at first if you try to make your own threads.
If you would like more control over execution and how the threads function you should take a look at the Task-Parallel-Library here: http://msdn.microsoft.com/en-us/library/dd460717.aspx Which has copious amount of information about multi-threading.
Also here is a great tutorial on how to create a C# thread: http://support.microsoft.com/default.aspx?scid=kb;en-us;815804
For an overview of asynchronous programming on Windows 8 in .Net 4.5:
http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
For .Net 4.0 and older you can use the ThreadPool
System.Threading.ThreadPool.QueueUserWorkItem(obj =>
{
// Do some work
for (int i = 0; i < 1000; i++)
Math.Sin(i);
// Get back to the UI thread
App.Current.MainWindow.Dispatcher.BeginInvoke(
new Action(delegate
{
block.Text = "Done!";
}));
});
I have a blog post that compares and contrasts various implementations of background tasks, with advantages and disadvantages for each. Spoiler: Task is definitely the best option. Also, I recommend Task.Run over TaskFactory.StartNew.
If your background operation is truly asynchronous, then you may not need any background threading at all. LINQPad has a set of async examples that are a great starting point. These are more up-to-date than the chapter on threading (by the same author) that others have recommended.
I got a code for calling async blocks.
private delegate void MyDelegate();
void Async(MyDelegate t) {
Thread thread = new Thread(new ThreadStart(t));
thread.IsBackground = true;
thread.Start();
}
And then:
Async(delegate() {
// code
});
I'm using it, but I'm sure that this is not the right way to do this. What are the problems with this method?
There seems no point in declaring your own delegate, for one thing. Why not just:
void Async(ThreadStart t) {
Thread thread = new Thread(t);
thread.IsBackground = true;
thread.Start();
}
? Personally I can't see myself wanting to do this often enough (and with no way of finding out how the task is progressing) to warrant a separate method. If you're using .NET 4 you should look into the Task Parallel Library, which still allows you to fire off asynchronous tasks - but in a rather more fully-featured way. (EDIT: Okay, so you can't use that from .NET 2 - it's worth bearing in mind for the future though.)
You might also want to consider using the BeginInvoke method on delegates, which allows you to start them on the thread pool easily anyway - and pass arguments:
Action<string, int> action = (name, age) => { ... };
IAsyncResult result = action.BeginInvoke("Jon", 35, null);
// Now you can use result if you want...
EDIT: You've now said you'll be doing this several times a second. Assuming this is a short-running task, you almost certainly should be using the thread-pool for this. As well as the example above, you can also use ThreadPool.QueueUserWorkItem to add a task to the thread pool. This will be more efficient (through thread reuse) than creating a new thread each time you have a task.
Since you already have a delegate
private delegate void MyDelegate();
you can do this
new MyDelegate(delegate
{
// code
}).BeginInvoke(null, null);
It'd use thread pool threads so you don't wind up overwhelming the runtime with too many threads.
Could anyone please give a sample or any link that describes how to spawn thread where each will do different work at the same time.
Suppose I have job1 and job2. I want to run both the jobs simultaneously. I need those jobs to get executed in parallel. how can I do that?
Well, fundamentally it's as simple as:
ThreadStart work = NameOfMethodToCall;
Thread thread = new Thread(work);
thread.Start();
...
private void NameOfMethodToCall()
{
// This will be executed on another thread
}
However, there are other options such as the thread pool or (in .NET 4) using Parallel Extensions.
I have a threading tutorial which is rather old, and Joe Alabahari has one too.
Threading Tutorial from MSDN!
http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx
Threads in C# are modelled by Thread Class. When a process starts (you run a program) you get a single thread (also known as the main thread) to run your application code. To explicitly start another thread (other than your application main thread) you have to create an instance of thread class and call its start method to run the thread using C#, Let's see an example
using System;
using System.Diagnostics;
using System.Threading;
public class Example
{
public static void Main()
{
//initialize a thread class object
//And pass your custom method name to the constructor parameter
Thread thread = new Thread(SomeMethod);
//start running your thread
thread.Start();
Console.WriteLine("Press Enter to terminate!");
Console.ReadLine();
}
private static void SomeMethod()
{
//your code here that you want to run parallel
//most of the cases it will be a CPU bound operation
Console.WriteLine("Hello World!");
}
}
You can learn more in this tutorial Multithreading in C#, Here you will learn how to take advantage of Thread class and Task Parallel Library provided by C# and .NET Framework to create robust applications that are responsive, parallel and meet the user expectations.
I need to do a sort of "timeout" or pause in my method for 10 seconds (10000 milliseconds), but I'm not sure if the following would work as i do not have multi-threading.
Thread.Sleep(10000);
I will try to use that current code, but I would appreciate if someone could explain the best and correct way of doing this, especially if the above code does not work properly. Thanks!
UPDATE: This program is actually a console application that in the function in question is doing many HTTPWebRequests to one server, so I wish to delay them for a specified amount of milliseconds. Thus, no callback is required - all that is needed is an "unconditional pause" - basically just the whole thing stops for 10 seconds and then keeps going. I'm pleased that C# still considers this as a thread, so Thread.Sleep(...) would work. Thanks everybody!
You may not have multi-threading, but you're still executing within a thread: all code executes in a thread.
Calling Thread.Sleep will indeed pause the current thread. Do you really want it to unconditionally pause for 10 seconds, or do you want to be able to be "woken up" by something else happening? If you're only actually using one thread, calling Sleep may well be the best way forward, but it will depend on the situation.
In particular, if you're writing a GUI app you don't want to use Thread.Sleep from the UI thread, as otherwise your whole app will become unresponsive for 10 seconds.
If you could give more information about your application, that would help us to advise you better.
Thread.Sleep is fine, and AFAIK the proper way. Even if you are not Multithreaded: There is always at least one Thread, and if you send that to sleep, it sleeps.
Another (bad) way is a spinlock, something like:
// Do never ever use this
private void DoNothing(){ }
private void KillCPU()
{
DateTime target = DateTime.Now.AddSeconds(10);
while(DateTime.Now < target) DoNothing();
DoStuffAfterWaiting10Seconds();
}
This is sadly still being used by people and while it will halt your program for 10 seconds, it will run at 100% CPU Utilization (Well, on Multi-Core systems it's one core).
That will indeed pause the executing thread/method for 10 seconds. Are you seeing a specific problem?
Note that you shouldn't Sleep the UI thread - it would be better to do a callback instead.
Note also that there are other ways of blocking a thread that allow simpler access to get it going again (if you find it is OK after 2s); such as Monitor.Wait(obj, 10000) (allowing another thread to Pulse if needed to wake it up):
static void Main() {
object lockObj = new object();
lock (lockObj) {
new Thread(GetInput).Start(lockObj);
Monitor.Wait(lockObj, 10000);
}
Console.WriteLine("Main exiting");
}
static void GetInput(object state) {
Console.WriteLine("press return...");
string s = Console.ReadLine();
lock (state) {
Monitor.Pulse(state);
}
Console.WriteLine("GetInput exiting");
}
You can do this with Thread.Interrupt too, but IMO that is messier.
You could use a separate thread to do it:
ThreadPool.QueueUserWorkItem(
delegate(object state)
{
Thread.Sleep(1000);
Console.WriteLine("done");
});
But, if this is a Windows Forms app, you will need to invoke the code after the delay from the Gui thread (this article, for example: How to update the GUI from another thread in C#?).
[Edit] Just saw your update. If it's a console app, then this will work. But if you haven't used multiple threads so far, then you need to be aware that this code will be executed in a different thread, which means you will have to take care about thread synchronization issues.
If you don't need background workers, stick to "keeping it simple".
Here is a pause class that will pause for the desired milliseconds and wont consume your CPU resources.
public class PauseClass
{
//(C) Michael Roberg
//Please feel free to distribute this class but include my credentials.
System.Timers.Timer pauseTimer = null;
public void BreakPause()
{
if (pauseTimer != null)
{
pauseTimer.Stop();
pauseTimer.Enabled = false;
}
}
public bool Pause(int miliseconds)
{
ThreadPriority CurrentPriority = Thread.CurrentThread.Priority;
if (miliseconds > 0)
{
Thread.CurrentThread.Priority = ThreadPriority.Lowest;
pauseTimer = new System.Timers.Timer();
pauseTimer.Elapsed += new ElapsedEventHandler(pauseTimer_Elapsed);
pauseTimer.Interval = miliseconds;
pauseTimer.Enabled = true;
while (pauseTimer.Enabled)
{
Thread.Sleep(10);
Application.DoEvents();
//pausThread.Sleep(1);
}
pauseTimer.Elapsed -= new ElapsedEventHandler(pauseTimer_Elapsed);
}
Thread.CurrentThread.Priority = CurrentPriority;
return true;
}
private void pauseTimer_Elapsed(object sender, ElapsedEventArgs e)
{
pauseTimer.Enabled = false;
}
}
Yes, that works just fine.
You don't have to have multiple threads to make use of some of the methods in the Thread class. You always have at least one thread.
For a timeout, you should have a static volatile boolean isRunning class field. When the new thread starts, the isRunning must become true, and at the end must become false.
The main thread should have a method that loops for the isRunning during the timeout you define. When the timeout ends, you should implement the logic. But, never use the abort thread method.
A pause... there isn't a straightforward solution. It depends on what you are doing inside the thread. However, you could look at Monitor.Wait.
If you can have an async method, you can do something like to pause the function at a certain location. Once pause is set false it will continue executing the rest of the code in the method. Since this is an async method and delay is async too UI execution wouldn't be affected.
* Please note that asyn is supported only in .net 4.5 and higher.
bool pause = true;
void async foo()
{
//some code
while (pause)
{
await Task.Delay(100);
}
//some code
}