Task.Run() doesn't raise exception?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-1















I have the following code in the



private void Button_Click(object sender, EventArgs e)
{
try
{
Task.Run(async () => await Presenter.Search());
}
catch (Exception ex)
{
LabelMessage.Text = "Error:....";
}
}


The function Presenter.Search() may get exceptions in some cases and I want to show an error message. However, the exception is not raised? I can only see it in the Visual studio debugger.










share|improve this question


















  • 2





    It runs async, you're not awaiting it, how is the Task.Run supposed to throw a exception which happens somewhen in the future?

    – tkausl
    Nov 16 '18 at 18:16


















-1















I have the following code in the



private void Button_Click(object sender, EventArgs e)
{
try
{
Task.Run(async () => await Presenter.Search());
}
catch (Exception ex)
{
LabelMessage.Text = "Error:....";
}
}


The function Presenter.Search() may get exceptions in some cases and I want to show an error message. However, the exception is not raised? I can only see it in the Visual studio debugger.










share|improve this question


















  • 2





    It runs async, you're not awaiting it, how is the Task.Run supposed to throw a exception which happens somewhen in the future?

    – tkausl
    Nov 16 '18 at 18:16














-1












-1








-1








I have the following code in the



private void Button_Click(object sender, EventArgs e)
{
try
{
Task.Run(async () => await Presenter.Search());
}
catch (Exception ex)
{
LabelMessage.Text = "Error:....";
}
}


The function Presenter.Search() may get exceptions in some cases and I want to show an error message. However, the exception is not raised? I can only see it in the Visual studio debugger.










share|improve this question














I have the following code in the



private void Button_Click(object sender, EventArgs e)
{
try
{
Task.Run(async () => await Presenter.Search());
}
catch (Exception ex)
{
LabelMessage.Text = "Error:....";
}
}


The function Presenter.Search() may get exceptions in some cases and I want to show an error message. However, the exception is not raised? I can only see it in the Visual studio debugger.







c# winforms






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 16 '18 at 18:14









ca9163d9ca9163d9

8,4952695212




8,4952695212








  • 2





    It runs async, you're not awaiting it, how is the Task.Run supposed to throw a exception which happens somewhen in the future?

    – tkausl
    Nov 16 '18 at 18:16














  • 2





    It runs async, you're not awaiting it, how is the Task.Run supposed to throw a exception which happens somewhen in the future?

    – tkausl
    Nov 16 '18 at 18:16








2




2





It runs async, you're not awaiting it, how is the Task.Run supposed to throw a exception which happens somewhen in the future?

– tkausl
Nov 16 '18 at 18:16





It runs async, you're not awaiting it, how is the Task.Run supposed to throw a exception which happens somewhen in the future?

– tkausl
Nov 16 '18 at 18:16












2 Answers
2






active

oldest

votes


















4














Really this should be written like so:



private async void Button_Click(object sender, EventArgs e)
{
try
{
await Presenter.Search();
}
catch (Exception ex)
{
LabelMessage.Text = "Error:....";
}
}


Now the call is awaited and the exception will be handled correctly. Note that you shouldn't typically use async void for the reasons listed here, but in the case of UI event handlers it's the recommended approach.






share|improve this answer
























  • My code is more complex than that. The code is actually kicked up by a timer in constructor. I think I will need to post a new question

    – ca9163d9
    Nov 16 '18 at 18:21






  • 2





    @ca9163d9 I think so too. Your question needs to accurately match what you need to do, as well as describe the circumstances involved (the timer).

    – Amy
    Nov 16 '18 at 18:24



















2














First of all, if Presenter.Search already returns a Task you should consider to make the event handler async and simply put



await Presenter.Search();


in the try-catch block.



The reason of Task.Run(Func<Task>) overload exists is that you can force an already existing Task to be scheduled for execution on a pool thread. This case can be justified in very rare cases as normally you should rely on the internal implementation of the Task returning methods. But if you know that an async method does not use threads (for example, just returns a Task, which will be completed on a specific event) and you are confident enough about forcing the execution on a pool thread you can do it this way. But also in this case you should await the external task; otherwise, the call is fire-and-forget and you will not catch anything:



await Task.Run(() => Presenter.Search());


Please note that I omitted the inner async-await:



await Task.Run(async () => await Presenter.Search());


This would also work and is functionally equivalent to the previous version but adds a needless inner state machine to the chain of tasks to execute.



TL;DR: Without knowing any further details await Presenter.Search(); seems to be the better solution but also await Task.Run(() => Presenter.Search()); can be justified if you know what you are doing.






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%2f53343322%2ftask-run-doesnt-raise-exception%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














    Really this should be written like so:



    private async void Button_Click(object sender, EventArgs e)
    {
    try
    {
    await Presenter.Search();
    }
    catch (Exception ex)
    {
    LabelMessage.Text = "Error:....";
    }
    }


    Now the call is awaited and the exception will be handled correctly. Note that you shouldn't typically use async void for the reasons listed here, but in the case of UI event handlers it's the recommended approach.






    share|improve this answer
























    • My code is more complex than that. The code is actually kicked up by a timer in constructor. I think I will need to post a new question

      – ca9163d9
      Nov 16 '18 at 18:21






    • 2





      @ca9163d9 I think so too. Your question needs to accurately match what you need to do, as well as describe the circumstances involved (the timer).

      – Amy
      Nov 16 '18 at 18:24
















    4














    Really this should be written like so:



    private async void Button_Click(object sender, EventArgs e)
    {
    try
    {
    await Presenter.Search();
    }
    catch (Exception ex)
    {
    LabelMessage.Text = "Error:....";
    }
    }


    Now the call is awaited and the exception will be handled correctly. Note that you shouldn't typically use async void for the reasons listed here, but in the case of UI event handlers it's the recommended approach.






    share|improve this answer
























    • My code is more complex than that. The code is actually kicked up by a timer in constructor. I think I will need to post a new question

      – ca9163d9
      Nov 16 '18 at 18:21






    • 2





      @ca9163d9 I think so too. Your question needs to accurately match what you need to do, as well as describe the circumstances involved (the timer).

      – Amy
      Nov 16 '18 at 18:24














    4












    4








    4







    Really this should be written like so:



    private async void Button_Click(object sender, EventArgs e)
    {
    try
    {
    await Presenter.Search();
    }
    catch (Exception ex)
    {
    LabelMessage.Text = "Error:....";
    }
    }


    Now the call is awaited and the exception will be handled correctly. Note that you shouldn't typically use async void for the reasons listed here, but in the case of UI event handlers it's the recommended approach.






    share|improve this answer













    Really this should be written like so:



    private async void Button_Click(object sender, EventArgs e)
    {
    try
    {
    await Presenter.Search();
    }
    catch (Exception ex)
    {
    LabelMessage.Text = "Error:....";
    }
    }


    Now the call is awaited and the exception will be handled correctly. Note that you shouldn't typically use async void for the reasons listed here, but in the case of UI event handlers it's the recommended approach.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 16 '18 at 18:19









    JohnJohn

    14.2k32645




    14.2k32645













    • My code is more complex than that. The code is actually kicked up by a timer in constructor. I think I will need to post a new question

      – ca9163d9
      Nov 16 '18 at 18:21






    • 2





      @ca9163d9 I think so too. Your question needs to accurately match what you need to do, as well as describe the circumstances involved (the timer).

      – Amy
      Nov 16 '18 at 18:24



















    • My code is more complex than that. The code is actually kicked up by a timer in constructor. I think I will need to post a new question

      – ca9163d9
      Nov 16 '18 at 18:21






    • 2





      @ca9163d9 I think so too. Your question needs to accurately match what you need to do, as well as describe the circumstances involved (the timer).

      – Amy
      Nov 16 '18 at 18:24

















    My code is more complex than that. The code is actually kicked up by a timer in constructor. I think I will need to post a new question

    – ca9163d9
    Nov 16 '18 at 18:21





    My code is more complex than that. The code is actually kicked up by a timer in constructor. I think I will need to post a new question

    – ca9163d9
    Nov 16 '18 at 18:21




    2




    2





    @ca9163d9 I think so too. Your question needs to accurately match what you need to do, as well as describe the circumstances involved (the timer).

    – Amy
    Nov 16 '18 at 18:24





    @ca9163d9 I think so too. Your question needs to accurately match what you need to do, as well as describe the circumstances involved (the timer).

    – Amy
    Nov 16 '18 at 18:24













    2














    First of all, if Presenter.Search already returns a Task you should consider to make the event handler async and simply put



    await Presenter.Search();


    in the try-catch block.



    The reason of Task.Run(Func<Task>) overload exists is that you can force an already existing Task to be scheduled for execution on a pool thread. This case can be justified in very rare cases as normally you should rely on the internal implementation of the Task returning methods. But if you know that an async method does not use threads (for example, just returns a Task, which will be completed on a specific event) and you are confident enough about forcing the execution on a pool thread you can do it this way. But also in this case you should await the external task; otherwise, the call is fire-and-forget and you will not catch anything:



    await Task.Run(() => Presenter.Search());


    Please note that I omitted the inner async-await:



    await Task.Run(async () => await Presenter.Search());


    This would also work and is functionally equivalent to the previous version but adds a needless inner state machine to the chain of tasks to execute.



    TL;DR: Without knowing any further details await Presenter.Search(); seems to be the better solution but also await Task.Run(() => Presenter.Search()); can be justified if you know what you are doing.






    share|improve this answer




























      2














      First of all, if Presenter.Search already returns a Task you should consider to make the event handler async and simply put



      await Presenter.Search();


      in the try-catch block.



      The reason of Task.Run(Func<Task>) overload exists is that you can force an already existing Task to be scheduled for execution on a pool thread. This case can be justified in very rare cases as normally you should rely on the internal implementation of the Task returning methods. But if you know that an async method does not use threads (for example, just returns a Task, which will be completed on a specific event) and you are confident enough about forcing the execution on a pool thread you can do it this way. But also in this case you should await the external task; otherwise, the call is fire-and-forget and you will not catch anything:



      await Task.Run(() => Presenter.Search());


      Please note that I omitted the inner async-await:



      await Task.Run(async () => await Presenter.Search());


      This would also work and is functionally equivalent to the previous version but adds a needless inner state machine to the chain of tasks to execute.



      TL;DR: Without knowing any further details await Presenter.Search(); seems to be the better solution but also await Task.Run(() => Presenter.Search()); can be justified if you know what you are doing.






      share|improve this answer


























        2












        2








        2







        First of all, if Presenter.Search already returns a Task you should consider to make the event handler async and simply put



        await Presenter.Search();


        in the try-catch block.



        The reason of Task.Run(Func<Task>) overload exists is that you can force an already existing Task to be scheduled for execution on a pool thread. This case can be justified in very rare cases as normally you should rely on the internal implementation of the Task returning methods. But if you know that an async method does not use threads (for example, just returns a Task, which will be completed on a specific event) and you are confident enough about forcing the execution on a pool thread you can do it this way. But also in this case you should await the external task; otherwise, the call is fire-and-forget and you will not catch anything:



        await Task.Run(() => Presenter.Search());


        Please note that I omitted the inner async-await:



        await Task.Run(async () => await Presenter.Search());


        This would also work and is functionally equivalent to the previous version but adds a needless inner state machine to the chain of tasks to execute.



        TL;DR: Without knowing any further details await Presenter.Search(); seems to be the better solution but also await Task.Run(() => Presenter.Search()); can be justified if you know what you are doing.






        share|improve this answer













        First of all, if Presenter.Search already returns a Task you should consider to make the event handler async and simply put



        await Presenter.Search();


        in the try-catch block.



        The reason of Task.Run(Func<Task>) overload exists is that you can force an already existing Task to be scheduled for execution on a pool thread. This case can be justified in very rare cases as normally you should rely on the internal implementation of the Task returning methods. But if you know that an async method does not use threads (for example, just returns a Task, which will be completed on a specific event) and you are confident enough about forcing the execution on a pool thread you can do it this way. But also in this case you should await the external task; otherwise, the call is fire-and-forget and you will not catch anything:



        await Task.Run(() => Presenter.Search());


        Please note that I omitted the inner async-await:



        await Task.Run(async () => await Presenter.Search());


        This would also work and is functionally equivalent to the previous version but adds a needless inner state machine to the chain of tasks to execute.



        TL;DR: Without knowing any further details await Presenter.Search(); seems to be the better solution but also await Task.Run(() => Presenter.Search()); can be justified if you know what you are doing.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 18:51









        taffertaffer

        8,70121536




        8,70121536






























            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%2f53343322%2ftask-run-doesnt-raise-exception%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

            Florida Star v. B. J. F.

            Error while running script in elastic search , gateway timeout

            Adding quotations to stringified JSON object values