Calling a synchronous method in an async fashion?












1















I'm developing an ASP.NET MVC WebApi project and one of the methods needs to make a LDAP search. The amount of information the search retrieves from the LDAP server ensures the call takes at least 7 seconds to complete. The call, as it uses the System.DirectoryServices.Protocols classes and methods, is synchronous and unmodifiable.



The amount of traffic this API will receive is rather big (even though the API is in an internal network) so 7 seconds for each call to the LDAP server is not a good idea. So I want to know this:




  • Is it a good idea to wrap this in an asynchronous method?

  • What's the proper way to async this call? (is await Task.Run(() => Search(params)) an acceptable way?)










share|improve this question




















  • 3





    Task.Run is not a great idea in ASP.Net MVC. Each request is it's own thread so you are not going to gain anything anyway.

    – Crowcoder
    Dec 28 '18 at 14:32






  • 1





    If the search takes 7s, perhaps you should sync the complete data you need to your own database once a day or so instead. And than query that.

    – Magnus
    Dec 28 '18 at 14:34













  • Making the call async will not speed up the response time for the client, it would just (possibly) reduce the amount of blocked threads on the server. So if the 7 seconds are problematic, you need to change the process overall, maybe with partial LDAP results or similar.

    – Lucero
    Dec 28 '18 at 14:36
















1















I'm developing an ASP.NET MVC WebApi project and one of the methods needs to make a LDAP search. The amount of information the search retrieves from the LDAP server ensures the call takes at least 7 seconds to complete. The call, as it uses the System.DirectoryServices.Protocols classes and methods, is synchronous and unmodifiable.



The amount of traffic this API will receive is rather big (even though the API is in an internal network) so 7 seconds for each call to the LDAP server is not a good idea. So I want to know this:




  • Is it a good idea to wrap this in an asynchronous method?

  • What's the proper way to async this call? (is await Task.Run(() => Search(params)) an acceptable way?)










share|improve this question




















  • 3





    Task.Run is not a great idea in ASP.Net MVC. Each request is it's own thread so you are not going to gain anything anyway.

    – Crowcoder
    Dec 28 '18 at 14:32






  • 1





    If the search takes 7s, perhaps you should sync the complete data you need to your own database once a day or so instead. And than query that.

    – Magnus
    Dec 28 '18 at 14:34













  • Making the call async will not speed up the response time for the client, it would just (possibly) reduce the amount of blocked threads on the server. So if the 7 seconds are problematic, you need to change the process overall, maybe with partial LDAP results or similar.

    – Lucero
    Dec 28 '18 at 14:36














1












1








1


0






I'm developing an ASP.NET MVC WebApi project and one of the methods needs to make a LDAP search. The amount of information the search retrieves from the LDAP server ensures the call takes at least 7 seconds to complete. The call, as it uses the System.DirectoryServices.Protocols classes and methods, is synchronous and unmodifiable.



The amount of traffic this API will receive is rather big (even though the API is in an internal network) so 7 seconds for each call to the LDAP server is not a good idea. So I want to know this:




  • Is it a good idea to wrap this in an asynchronous method?

  • What's the proper way to async this call? (is await Task.Run(() => Search(params)) an acceptable way?)










share|improve this question
















I'm developing an ASP.NET MVC WebApi project and one of the methods needs to make a LDAP search. The amount of information the search retrieves from the LDAP server ensures the call takes at least 7 seconds to complete. The call, as it uses the System.DirectoryServices.Protocols classes and methods, is synchronous and unmodifiable.



The amount of traffic this API will receive is rather big (even though the API is in an internal network) so 7 seconds for each call to the LDAP server is not a good idea. So I want to know this:




  • Is it a good idea to wrap this in an asynchronous method?

  • What's the proper way to async this call? (is await Task.Run(() => Search(params)) an acceptable way?)







c# asp.net-web-api async-await ldap-query






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 28 '18 at 14:28







Léster

















asked Dec 28 '18 at 14:22









LésterLéster

341421




341421








  • 3





    Task.Run is not a great idea in ASP.Net MVC. Each request is it's own thread so you are not going to gain anything anyway.

    – Crowcoder
    Dec 28 '18 at 14:32






  • 1





    If the search takes 7s, perhaps you should sync the complete data you need to your own database once a day or so instead. And than query that.

    – Magnus
    Dec 28 '18 at 14:34













  • Making the call async will not speed up the response time for the client, it would just (possibly) reduce the amount of blocked threads on the server. So if the 7 seconds are problematic, you need to change the process overall, maybe with partial LDAP results or similar.

    – Lucero
    Dec 28 '18 at 14:36














  • 3





    Task.Run is not a great idea in ASP.Net MVC. Each request is it's own thread so you are not going to gain anything anyway.

    – Crowcoder
    Dec 28 '18 at 14:32






  • 1





    If the search takes 7s, perhaps you should sync the complete data you need to your own database once a day or so instead. And than query that.

    – Magnus
    Dec 28 '18 at 14:34













  • Making the call async will not speed up the response time for the client, it would just (possibly) reduce the amount of blocked threads on the server. So if the 7 seconds are problematic, you need to change the process overall, maybe with partial LDAP results or similar.

    – Lucero
    Dec 28 '18 at 14:36








3




3





Task.Run is not a great idea in ASP.Net MVC. Each request is it's own thread so you are not going to gain anything anyway.

– Crowcoder
Dec 28 '18 at 14:32





Task.Run is not a great idea in ASP.Net MVC. Each request is it's own thread so you are not going to gain anything anyway.

– Crowcoder
Dec 28 '18 at 14:32




1




1





If the search takes 7s, perhaps you should sync the complete data you need to your own database once a day or so instead. And than query that.

– Magnus
Dec 28 '18 at 14:34







If the search takes 7s, perhaps you should sync the complete data you need to your own database once a day or so instead. And than query that.

– Magnus
Dec 28 '18 at 14:34















Making the call async will not speed up the response time for the client, it would just (possibly) reduce the amount of blocked threads on the server. So if the 7 seconds are problematic, you need to change the process overall, maybe with partial LDAP results or similar.

– Lucero
Dec 28 '18 at 14:36





Making the call async will not speed up the response time for the client, it would just (possibly) reduce the amount of blocked threads on the server. So if the 7 seconds are problematic, you need to change the process overall, maybe with partial LDAP results or similar.

– Lucero
Dec 28 '18 at 14:36












2 Answers
2






active

oldest

votes


















4














As noted in the comment I don't see how making the call asynchronous would help at all. Running it in another thread and awaiting (as per your "what is the proper way..." question) does use as many resources as synchronously calling and waiting.



Note, however, that the System.DirectoryServices.Protocols classes such as LdapCollection do have async support with the older APM (Asynchronous Programming Model) style (e.g. BeginSendRequest/EndSendRequest).



You can easily wrap APM-style APIs to awaitable Task-based style by using TaskFactory<TResult>.FromAsync, this would be the "proper way" of using these classes with async. See also Interop with Other Asynchronous Patterns and Types.






share|improve this answer
























  • Used your advice to reimplement the method in an async fashion and it worked flawlessly. Of course, as you said, there was no real gain in speed, but that was solved when I was told that I could discard most of the requested data (adjusting the query to retrieve only what was needed reduced the execution time to bit under 3 seconds and subsequent queries seem to be cached).

    – Léster
    Dec 28 '18 at 17:31













  • @Léster Thank you for the feedback, glad to know my reply helped somewhat. :)

    – Lucero
    Dec 28 '18 at 22:46



















0














PD: Based on Lucero's answer, here's an extension method that hides the APM calls and exposes itself as a regular Task<T> async method:



public static async Task<DirectoryResponse> SendRequestAsync(this LdapConnection conn, string target, string filter,
SearchScope searchScope, params string attributeList)
{
if (conn == null)
{
throw new NullReferenceException();
}
var search_request = new SearchRequest(target, filter, searchScope, attributeList);
var response = await Task<DirectoryResponse>.Factory.FromAsync(
conn.BeginSendRequest,
(iar) => conn.EndSendRequest(iar),
search_request,
PartialResultProcessing.NoPartialResultSupport,
null);
return response;
}


This can also be used as a starting point for your own needs (you can use a similar method to "make" APM-supporting objects behave in Task-based style).






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53959976%2fcalling-a-synchronous-method-in-an-async-fashion%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    As noted in the comment I don't see how making the call asynchronous would help at all. Running it in another thread and awaiting (as per your "what is the proper way..." question) does use as many resources as synchronously calling and waiting.



    Note, however, that the System.DirectoryServices.Protocols classes such as LdapCollection do have async support with the older APM (Asynchronous Programming Model) style (e.g. BeginSendRequest/EndSendRequest).



    You can easily wrap APM-style APIs to awaitable Task-based style by using TaskFactory<TResult>.FromAsync, this would be the "proper way" of using these classes with async. See also Interop with Other Asynchronous Patterns and Types.






    share|improve this answer
























    • Used your advice to reimplement the method in an async fashion and it worked flawlessly. Of course, as you said, there was no real gain in speed, but that was solved when I was told that I could discard most of the requested data (adjusting the query to retrieve only what was needed reduced the execution time to bit under 3 seconds and subsequent queries seem to be cached).

      – Léster
      Dec 28 '18 at 17:31













    • @Léster Thank you for the feedback, glad to know my reply helped somewhat. :)

      – Lucero
      Dec 28 '18 at 22:46
















    4














    As noted in the comment I don't see how making the call asynchronous would help at all. Running it in another thread and awaiting (as per your "what is the proper way..." question) does use as many resources as synchronously calling and waiting.



    Note, however, that the System.DirectoryServices.Protocols classes such as LdapCollection do have async support with the older APM (Asynchronous Programming Model) style (e.g. BeginSendRequest/EndSendRequest).



    You can easily wrap APM-style APIs to awaitable Task-based style by using TaskFactory<TResult>.FromAsync, this would be the "proper way" of using these classes with async. See also Interop with Other Asynchronous Patterns and Types.






    share|improve this answer
























    • Used your advice to reimplement the method in an async fashion and it worked flawlessly. Of course, as you said, there was no real gain in speed, but that was solved when I was told that I could discard most of the requested data (adjusting the query to retrieve only what was needed reduced the execution time to bit under 3 seconds and subsequent queries seem to be cached).

      – Léster
      Dec 28 '18 at 17:31













    • @Léster Thank you for the feedback, glad to know my reply helped somewhat. :)

      – Lucero
      Dec 28 '18 at 22:46














    4












    4








    4







    As noted in the comment I don't see how making the call asynchronous would help at all. Running it in another thread and awaiting (as per your "what is the proper way..." question) does use as many resources as synchronously calling and waiting.



    Note, however, that the System.DirectoryServices.Protocols classes such as LdapCollection do have async support with the older APM (Asynchronous Programming Model) style (e.g. BeginSendRequest/EndSendRequest).



    You can easily wrap APM-style APIs to awaitable Task-based style by using TaskFactory<TResult>.FromAsync, this would be the "proper way" of using these classes with async. See also Interop with Other Asynchronous Patterns and Types.






    share|improve this answer













    As noted in the comment I don't see how making the call asynchronous would help at all. Running it in another thread and awaiting (as per your "what is the proper way..." question) does use as many resources as synchronously calling and waiting.



    Note, however, that the System.DirectoryServices.Protocols classes such as LdapCollection do have async support with the older APM (Asynchronous Programming Model) style (e.g. BeginSendRequest/EndSendRequest).



    You can easily wrap APM-style APIs to awaitable Task-based style by using TaskFactory<TResult>.FromAsync, this would be the "proper way" of using these classes with async. See also Interop with Other Asynchronous Patterns and Types.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Dec 28 '18 at 14:44









    LuceroLucero

    51.7k592142




    51.7k592142













    • Used your advice to reimplement the method in an async fashion and it worked flawlessly. Of course, as you said, there was no real gain in speed, but that was solved when I was told that I could discard most of the requested data (adjusting the query to retrieve only what was needed reduced the execution time to bit under 3 seconds and subsequent queries seem to be cached).

      – Léster
      Dec 28 '18 at 17:31













    • @Léster Thank you for the feedback, glad to know my reply helped somewhat. :)

      – Lucero
      Dec 28 '18 at 22:46



















    • Used your advice to reimplement the method in an async fashion and it worked flawlessly. Of course, as you said, there was no real gain in speed, but that was solved when I was told that I could discard most of the requested data (adjusting the query to retrieve only what was needed reduced the execution time to bit under 3 seconds and subsequent queries seem to be cached).

      – Léster
      Dec 28 '18 at 17:31













    • @Léster Thank you for the feedback, glad to know my reply helped somewhat. :)

      – Lucero
      Dec 28 '18 at 22:46

















    Used your advice to reimplement the method in an async fashion and it worked flawlessly. Of course, as you said, there was no real gain in speed, but that was solved when I was told that I could discard most of the requested data (adjusting the query to retrieve only what was needed reduced the execution time to bit under 3 seconds and subsequent queries seem to be cached).

    – Léster
    Dec 28 '18 at 17:31







    Used your advice to reimplement the method in an async fashion and it worked flawlessly. Of course, as you said, there was no real gain in speed, but that was solved when I was told that I could discard most of the requested data (adjusting the query to retrieve only what was needed reduced the execution time to bit under 3 seconds and subsequent queries seem to be cached).

    – Léster
    Dec 28 '18 at 17:31















    @Léster Thank you for the feedback, glad to know my reply helped somewhat. :)

    – Lucero
    Dec 28 '18 at 22:46





    @Léster Thank you for the feedback, glad to know my reply helped somewhat. :)

    – Lucero
    Dec 28 '18 at 22:46













    0














    PD: Based on Lucero's answer, here's an extension method that hides the APM calls and exposes itself as a regular Task<T> async method:



    public static async Task<DirectoryResponse> SendRequestAsync(this LdapConnection conn, string target, string filter,
    SearchScope searchScope, params string attributeList)
    {
    if (conn == null)
    {
    throw new NullReferenceException();
    }
    var search_request = new SearchRequest(target, filter, searchScope, attributeList);
    var response = await Task<DirectoryResponse>.Factory.FromAsync(
    conn.BeginSendRequest,
    (iar) => conn.EndSendRequest(iar),
    search_request,
    PartialResultProcessing.NoPartialResultSupport,
    null);
    return response;
    }


    This can also be used as a starting point for your own needs (you can use a similar method to "make" APM-supporting objects behave in Task-based style).






    share|improve this answer




























      0














      PD: Based on Lucero's answer, here's an extension method that hides the APM calls and exposes itself as a regular Task<T> async method:



      public static async Task<DirectoryResponse> SendRequestAsync(this LdapConnection conn, string target, string filter,
      SearchScope searchScope, params string attributeList)
      {
      if (conn == null)
      {
      throw new NullReferenceException();
      }
      var search_request = new SearchRequest(target, filter, searchScope, attributeList);
      var response = await Task<DirectoryResponse>.Factory.FromAsync(
      conn.BeginSendRequest,
      (iar) => conn.EndSendRequest(iar),
      search_request,
      PartialResultProcessing.NoPartialResultSupport,
      null);
      return response;
      }


      This can also be used as a starting point for your own needs (you can use a similar method to "make" APM-supporting objects behave in Task-based style).






      share|improve this answer


























        0












        0








        0







        PD: Based on Lucero's answer, here's an extension method that hides the APM calls and exposes itself as a regular Task<T> async method:



        public static async Task<DirectoryResponse> SendRequestAsync(this LdapConnection conn, string target, string filter,
        SearchScope searchScope, params string attributeList)
        {
        if (conn == null)
        {
        throw new NullReferenceException();
        }
        var search_request = new SearchRequest(target, filter, searchScope, attributeList);
        var response = await Task<DirectoryResponse>.Factory.FromAsync(
        conn.BeginSendRequest,
        (iar) => conn.EndSendRequest(iar),
        search_request,
        PartialResultProcessing.NoPartialResultSupport,
        null);
        return response;
        }


        This can also be used as a starting point for your own needs (you can use a similar method to "make" APM-supporting objects behave in Task-based style).






        share|improve this answer













        PD: Based on Lucero's answer, here's an extension method that hides the APM calls and exposes itself as a regular Task<T> async method:



        public static async Task<DirectoryResponse> SendRequestAsync(this LdapConnection conn, string target, string filter,
        SearchScope searchScope, params string attributeList)
        {
        if (conn == null)
        {
        throw new NullReferenceException();
        }
        var search_request = new SearchRequest(target, filter, searchScope, attributeList);
        var response = await Task<DirectoryResponse>.Factory.FromAsync(
        conn.BeginSendRequest,
        (iar) => conn.EndSendRequest(iar),
        search_request,
        PartialResultProcessing.NoPartialResultSupport,
        null);
        return response;
        }


        This can also be used as a starting point for your own needs (you can use a similar method to "make" APM-supporting objects behave in Task-based style).







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 2 at 14:46









        LésterLéster

        341421




        341421






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53959976%2fcalling-a-synchronous-method-in-an-async-fashion%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas