Middle — Middle+
How can resource-intensive tasks be organized to run without blocking the main execution thread?
sobes.tech AI
Answer from AI
In C#, to perform resource-intensive tasks without blocking the main thread, asynchronous programming with the keywords async and await and tasks (Task) is usually used. This allows operations to run in the background thread without blocking the UI or main thread.
Example:
public async Task<int> CalculateAsync()
{
return await Task.Run(() => {
// Long resource-intensive operation
Thread.Sleep(5000);
return 42;
});
}
Here, Task.Run starts the work in a thread pool, and await allows not to block the calling thread while the task is running.
You can also use BackgroundWorker or create separate threads manually, but Task and async/await are a more modern and convenient approach.