M
M
Michael2016-11-02 09:31:19
.NET
Michael, 2016-11-02 09:31:19

Are threads busy when using async/await?

Is there a difference between

Task.Run(() => {
 ... long wait IO bound operation
});

and
await LongIOBoundOperaion();
In the first case, the thread will be busy waiting for the completion of the IO operation, and in the second, will some thread wait for execution or will the thread be created (taken free from the pool) after notification that the IO operation has completed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Nemiro, 2016-11-02
@Sing303

https://msdn.microsoft.com/en-us/library/hh156528.aspx
The Task.Run method queues the given task to run on the thread pool.
Those. in the first case, you will simply add a task to the execution queue and continue the execution of the program (without waiting, the program may complete work before the created task). And in the second, the current thread will wait for the completion of the asynchronous operation. The main thread will not be frozen when await is used.

// без ожидания
Console.WriteLine(DateTime.Now);

Task.Run(() => { Thread.Sleep(5000); });

// этот код будет выполнен сразу
Console.WriteLine(DateTime.Now);

// ожидание с await
Console.WriteLine(DateTime.Now);

await Task.Run(() => { Thread.Sleep(5000); });

// этот код будет выполнен, только после завершения выполнения задачи
// текущий (вызывающий) поток не будет приостановлен
// (например, в Windows Form это будет хорошо видно)
Console.WriteLine(DateTime.Now);

If you make a task and call the Wait method , the main thread will be suspended until the task is completed.
Console.WriteLine(DateTime.Now);

var t = Task.Run(() => { Thread.Sleep(5000); });
t.Wait(); // ожидание выполнения задачи

// этот код будет выполнен, только после завершения выполнения задачи
// текущий (вызывающий) поток будет блокирован
// (например, в Windows Form это будет хорошо видно)
Console.WriteLine(DateTime.Now);

74ad1b048cee439faab48113a61a7ec7.gif

Y
yuras666, 2017-01-11
@yuras666

You hide all the logic for the slider in a separate file. Further, you only activate this component as needed. There can be a whole bunch of implementations of this:
1) Function - constructor https://learn.javascript.ru/widgets-structure
2) JQuery plugin https://habrahabr.ru/post/153099 . But jquery is no longer fashionable this season :(
3) Frameworks like react or vuejs (but for the sake of one slider this is superfluous)
If the project is complex, you study the topic of modules (common, es6, module template, etc.) and DI. Further organization will already depend on the project and the framework.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question