There is a certain task by which it is necessary to process data in an array of a large number of elements. The data is the cadastral numbers for which you need to request data from a certain site.

There is also a form on which the ProgressBar and two labels's lie, which show the number of processed numbers and how many numbers in total.

Then everything is like this:

private async void CnfBtnOkClick(object sender, EventArgs e) { // ... // cnumbers - string[] с Π½ΠΎΠΌΠ΅Ρ€Π°ΠΌΠΈ await ParseNumbersAsync?.Invoke(cnumbers, threadCount).ConfigureAwait(true); //... } 

Somewhere in the presenter

 private async Task ParseNumbersAsync(string[] cnumbers, int threadcount) { // Π”Π΅Π»ΠΈΠΌ массив Π½Π° нСсколько массивов ΠΏΠΎ количСству ΠΏΠΎΡ‚ΠΎΠΊΠΎΠ² string[][] datas = cnumbers.Split(threadcount); Task[] tsk = new Task[threadcount]; for(int i = 0; i < threadcount; i++) { tsk[i] = Task.Factory.StartNew(() => DoWork(datas[i]), TaskCreationOptions.LongRunning); } await Task.WhenAll(tsk).ConfigureAwait(true); } 

Inside DoWork is a number loop, and inside a loop is a construction

 Task.Factory.StartNew(() => UpdateUI, CancellationToken.None, TaskCreationOptions.None, _ts); 

Inside UpdateUI progressBar.PerfomStep and update labels. And everything works fine.

But then I decided to rewrite the application through the MVP pattern on WinForms. I transferred ParseNumbersAsync to the presenter, and DoWork lies in the model.

But it is not clear how, in this case, to update the UI from DoWork? Tried through the context and Post, tried through Invoke and through Task.Factory.StartNew, but the application starts to work as if it is synchronous, the form cannot even be moved. It is necessary to book a method for updating the UI and asynchrony appears again.

I can do simple applications with UI with asynchronous operations, and when I have to get to the UI in a couple of layers, I still don’t understand how to do it.

  • one
    In a multi-layered architecture, a couple of layers is not very good to do, but when it is necessary, they use the observer pattern. - AK ♦
  • And if for some reason it is necessary to sneak through a couple of layers, how is it necessary to implement this so that the asynchrony is not violated? - Lev Limin

0