For example:
async Task WriteAsync(IProgress<string> progress) { DateTime nextReportTime = DateTime.Now + TimeSpan.FromSeconds(10); while (true) { if (DateTime.Now > nextReportTime) { progress.Report(тут ваши данные); nextReportTime = DateTime.Now + TimeSpan.FromSeconds(10); } // что-то делаем... await Task.Delay(100); } }
The external code will pass its Progress<T> to the method, and will receive results from it. Instead of string you can, of course, take any T
A more accurate version (it interrupts a pause of 100 milliseconds if the time for the report has come):
async Task WriteAsync(IProgress<string> progress) { Task waitNextReportTime = Task.Delay(TimeSpan.FromSeconds(10)); while (true) { // что-то делаем... var pauseTask = Task.Delay(100); await Task.WhenAny(waitNextReportTime, pauseTask); if (waitNextReportTime.IsCompleted) { progress.Report(тут ваши данные); waitNextReportTime = Task.Delay(TimeSpan.FromSeconds(10)); } await pauseTask; } }
For the case when it is necessary to give the measurement result only once, the following modification will do:
async Task WriteAsync(IProgress<string> progress) { Task waitReportTime = Task.Delay(TimeSpan.FromSeconds(10)); while (true) { // что-то делаем... var pauseTask = Task.Delay(100); if (waitReportTime != null) { await Task.WhenAny(waitReportTime, pauseTask); if (waitReportTime.IsCompleted) { waitReportTime = null; progress.Report(тут ваши данные); } } await pauseTask; } }
await Task.Delay. 2) Zdacha quite common and it can be solved in different ways, can you specify? - Vasek