I want to run threads in parallel for some task using C#. I have attached the photo of what I am trying but still the threads are running at different time at millisecond level is it possible to run a exact same time.
I am using Parallel.For
, is their something else which can help.
Abhay Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
you can try std::thread
void foo(param) {
// Statements
}
std::thread thread_obj(foo, params);
search more online you’ll find related documentations.
Probably not the answer you are looking for, but as good starting point is to rely on lazy enumeration and Task.WhenAll
implementation:
using System.Diagnostics;
var enumerable = Enumerable.Range(1, 2).Select(x => Task.Run(() =>
{
Console.WriteLine($"TS: {DateTime.FromBinary(Stopwatch.GetTimestamp()):O}");
}));
foreach (var _ in Enumerable.Range(1, 10))
{
await Task.WhenAll(enumerable);
Console.WriteLine();
}
On my machine i see the following results:
TS: 0004-07-30T02:51:42.2084062
TS: 0004-07-30T02:51:42.2084982
TS: 0004-07-30T02:51:43.7640029
TS: 0004-07-30T02:51:43.7647039
TS: 0004-07-30T02:51:43.7713316
TS: 0004-07-30T02:51:43.7707357
TS: 0004-07-30T02:51:43.7741436
TS: 0004-07-30T02:51:43.7754675
TS: 0004-07-30T02:51:43.7766885
TS: 0004-07-30T02:51:43.7767815
TS: 0004-07-30T02:51:43.7779784
TS: 0004-07-30T02:51:43.7783654
A bit of manual calculation based on couple samples shows difference with
range of 100-600 microseconds. Actual timestamps might or might not fall into the same millisecond.
So, it is up to you to decide to use that or not.