Using C#, create a class which gets an action (parameter-less delegate) in its construction and has a single public method
bool execute()
which does the following:
Executes the action only if no other thread is currently executing the action
If another thread is already executing, wait until thread is finished before returning (but without executing action again)
Return true if current thread executes that action, otherwise return 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 the above piece of code correct? Please give me your feedback.
Please don't think that this is just exercise. This question was asked by one of the interviewers.
wait until thread finished before returning
- I do not see any code which will do it.create class which get an action (parameter less delegate) in its construction
- you didn't show any class or constructor in your code. It's hard to review your code, it has some weird logic (Thread.CurrentThread.Name == null
) and I do not see what this code should do. \$\endgroup\$