Asynchronous design issue



  • Many of us have faced the need to calculate any value in the method many times. The value to be counted shall be stored elsewhere (e.g. in the class statistic field). For multi-point algorithms, it's:

    lock (syncObj)
    Interlocked.Increment(ref int)
    

    But for asynchronous methods, any blocking of the method is very undesirable. I tried to turn around on a basis. BlockingCollection - but unfortunately, the methods are very fast and the speed of transmission is short.

    How can you get out of this position?



  • I will discuss the comments in response.

    If it comes to asynchronous code, it makes sense not to produce side effects. Like because they need synchronization.

    I would therefore recommend other approaches, depending on whether meaning I don't know.

    • If the enumerator is needed to compile any information that is derived from the distance of the method, it is worth returning the enumerator ' s increments as part of the return. In the end, it's part of the result.
    • If the counter is needed to report process Function avoidance should be transferred IProgress<T>and have the function report progress through it. Standard implementation Progress<T> Marshals values in UI flow, and thus shall not interfere with the calculation.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2