Good day! I ask for help from the expert community.

We need a template (sample code) to solve the following problem:

Some long-term task is being performed asynchronously, the intermediate results of which are displayed in the GUI and when some controls of the same form change, new values ​​fall into the asynchronously started method (running in a stream other than the GUI thread).

There are plenty of examples for the first part of the task (displaying intermediate results), but I did not find the data transfer from the GUI to the method asynchronously found.

Tools: MS VISUAL C #, WINFORMS application. For the organization of asynchrony isp. Async / await construction

Thank you in advance.

1 answer 1

It's not entirely clear why your asynchronous method is not running in a UI stream. But let's say you need it. Then you can retrieve data from the UI stream independently using the dispatcher. Example:

async Task BackgroundComputation() { var oldValue = ""; while (true) { await Task.Delay(1000); var newValue = await Dispatcher.InvokeAsync(() => InputInfo.Text); if (oldValue != newValue) { Console.WriteLine(newValue); oldValue = newValue; } } } 

(run via Task.Run(BackgroundComputation); )

Here InputInfo is a TextBox in which the user enters text. Using the await Dispatcher.InvokeAsync(() => InputInfo.Text) InputInfo.Text value InputInfo.Text read in the UI thread and delivered to the workflow.

As to how to deliver the results of work in the UI-stream, probably the best thing to do is to use the Progress<T> class.

  • Не вполне ясно, зачем ваш асинхронный метод бежит не в UI-потоке. in order not to hang the interface ... - Ev_Hyper
  • one
    @Ev_Hyper: Well, you just don't have to do a blocking wait in it. For example, on stream.Read , and await stream.ReadAsync . Well, the processor-intensive operations to take to the sub-cache through result = await Task.Run(() => CpuBoundCode()) . - VladD
  • This is obvious :) - Ev_Hyper
  • @Ev_Hyper: Well. And if the code is so structured, then there are no problems with accessing UI controls or VM objects; a large, control part of the code, besides calculations, runs in the UI thread. - VladD