Please let me know the below piece of code is correct or not
Using C#, create class which get an action (parameter less delegate) in its construction and has a single public method ‘bool execute()’ which does following:
• Execute the action only if no other thread is currently executing the action.
• If another thread is already executing, wait until thread finished before returning (but without executing action again)
• Return true if current thread that action, otherwise false.
public delegate bool Action();
private static int ThreadsCount = 100; //initialize threads count
static void Main(string[] args)
{
Action act = Execute;
bool t = act();
Console.WriteLine(t);
Console.ReadLine();
}
static bool Execute()
{
bool retVal = false;
Thread thread = Thread.CurrentThread;
string s = thread.Name;
if (s == null)
{
test();
retVal = true;
}
else
{
ThreadsCount = ThreadsCount - 1;
if (ThreadsCount < 1)
{
//if all threads finished executing do whatever you wanna do here..
Console.WriteLine("C# language");
test();
retVal = true;
}
else
{
retVal = false;
}
}
return retVal;
}
private static void test()
{
Console.WriteLine("C# language");
}
Is it correct the above piece of code? Please give me your feed back.
Please don't think that this is just exercise. This question asked by one of the interviewer. Sorry if my English is not in correct form.
- 31
- 1
- 1
- 2