The program needs to perform some operations in a separate stream, such as sending a request to the server and waiting for a response from it.
For implementation I use the Dataflow library in order to do this all in a sequence.

Implemented this class:

 partial class PoolManager { CancellationTokenSource CT; TransformBlock<Func<string>, string> ActionBlock; public PoolManager() { PM = this; CT = new CancellationTokenSource(); ActionBlock = new TransformBlock<Func<string>, string>(async n => { await Task.Delay(2000); string a = ""; try { a = n(); } catch (Exception e) { } return a; }, new ExecutionDataflowBlockOptions { CancellationToken = CT.Token }); } public void Add(Action func, string message) { ActionBlock.Post(new Func<string>(delegate () { func(); return message; })); } } 

And the whole works as it should, but when I send a function to it, inside of which there is a sending and waiting for an answer, then at the time of waiting, the program interface hangs. On average, this is 100ms , sometimes it reaches 500ms or 1000ms , which becomes very noticeable. I do not understand what the reason is, for it should go in a separate stream.

  • It doesn't look like the problem is in the code above. I think you should look somewhere higher. PS Why do you need Dataflow for one step at all? - andreycha
  • @andreycha I looked through the entire hierarchy of called functions that I could, and everything ends on a synchronous function that makes a query and returns a Json string. And that is where the delay. In those functions that I send to the Dataflow block, there is more than one step. - BwehaaFox
  • @andreycha: Dataflow I probably advised in some of the comments. - VladD
  • @VladD, yes. For my task, he really is more comfortable. - BwehaaFox
  • @BwehaaFox: What is your “entry point”? What do you run, after which the program hangs? - VladD

1 answer 1

The question was resolved by itself.


In general, this code works quite correctly, and the problem lurked deeper.

In a specific task on which I tested this code, a function in the UserControl control was sent to TransformBlock . In this function, the class instance method was called, and this method sent a request to the server and waited for a response. The method was synchronous and therefore the thread in which it was called should have been blocked . In order that this was not done in a parallel stream, but the main stream was still blocked.

As a result, I noticed that the code in the function being sent is executed via the Dispatcher , so that I can fill the ProgressBar , and therefore, I checked the thread number through Thread.CurrentThread.ManagedThreadId , when I entered the function and the dispatcher, I realized that the code inside the Dispatcher is already running in the UI stream, and not in the TransformBlock stream, it was from that request that it passed in the UI stream, which caused the hang.

Thanks VladD , for the help in solving this problem.