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.