I have a list of a object “Code”:
List<Code> listCodes = new List<Code>();
I need to execute each code inside the list in a Thread, but I have not idea how to do that, because I tried to do something like:
foreach(Code c in listCodes)
{
Thread tr = new Thread(delegate() {
Execute(c.CodeLine);
});
}
This foreach is in a timer, because those Codes will be executed all the time, but when I do that the same code is executed a lot of times even if the first execution wasn’t finished, if the code takes like 5 seconds to be executed and finished and the timer is 500ms it will be executed 10 times if I disable the timer after 5 seconds for exemple.
I couldn’t think anything to execute the codes in the list, each one in their thread, but I want to execute the thread of the code 0(for exemple) only if it was finished after the execution.
Thank you.
System.Threading.Monitor.TryEnteris perfect for the job:What it does is try to acquire an exclusive lock on the
Codeobject. If it can’t (i.e. theCodeis already executing) then nothing will happen; otherwise, the lock is acquired, and released when execution is complete.