Junior — Middle
Have you had experience writing code that uses multithreading mechanisms?
sobes.tech AI
Answer from AI
Yes, I have experience writing multithreaded code in C#. For working with threads, I used classes from the System.Threading namespace, such as Thread, Task, as well as synchronization mechanisms (lock, Mutex, Semaphore).
An example of using Task to run a parallel operation:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
Task<int> task = Task.Run(() => {
// Some long-running operation
int sum = 0;
for (int i = 0; i < 1000000; i++)
sum += i;
return sum;
});
int result = await task;
Console.WriteLine($"Sum: {result}");
}
}
I also used lock to protect shared resources from concurrent access:
private static readonly object _locker = new object();
void IncrementCounter()
{
lock(_locker)
{
// Critical section
counter++;
}
}
This allows efficient use of multithreading and avoids race condition issues.