C# Handling Task Cancellations/Timeouts and Exceptions












1












$begingroup$


I am very new to Tasks and therefore new to handling task cancellations and task exceptions.



I wrote this method that gets a List which is then used to populate an ObsservableCollection shown in a ListView but I am not sure if I am handling cancellations and exceptions properly.



I would like to cancel awaited tasks if they dont execute successfuly within 10 seconds time frame. In addition, I would like to handle any exceptions and to properly release any resources, hence I am using the "using" statements below.



public override async Task<IList<MyModel>> GetDataAsync(string Id)
{
try
{
// 1. Connecting TcpClient may take up to 90sec? How to time that to 10sec?
using (TcpClient client = new TcpClient(ip, port))
using (NetworkStream stream = client.GetStream())
{
byte messageBytes = GetMessageBytes(Id);

using (var writeCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
{
await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
await stream.FlushAsync(); // 2. Do I even need this?
}

byte buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
int bytesRead = 0;

using (var readCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
{
while (stream.DataAvailable)
{
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, readCts.Token);
builder.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
}
}

string msg = receivedMessage.ToString();
}

return ParseMessageIntoList(msg); // parses message into IList<MyModel>
}
catch (OperationCancelledException ex1)
{
// 3. If 10 second timeout expires, I expect to hit this catch block but I dont see it happen?
Debug.WriteLine(ex.Message);
}
catch (Exception ex2)
{
// Catch any other exception and return empty list
return await Task.FromResult<IList<MyModel>>(new List<MyModel>());
}
}









share|improve this question







New contributor




cd491415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    1












    $begingroup$


    I am very new to Tasks and therefore new to handling task cancellations and task exceptions.



    I wrote this method that gets a List which is then used to populate an ObsservableCollection shown in a ListView but I am not sure if I am handling cancellations and exceptions properly.



    I would like to cancel awaited tasks if they dont execute successfuly within 10 seconds time frame. In addition, I would like to handle any exceptions and to properly release any resources, hence I am using the "using" statements below.



    public override async Task<IList<MyModel>> GetDataAsync(string Id)
    {
    try
    {
    // 1. Connecting TcpClient may take up to 90sec? How to time that to 10sec?
    using (TcpClient client = new TcpClient(ip, port))
    using (NetworkStream stream = client.GetStream())
    {
    byte messageBytes = GetMessageBytes(Id);

    using (var writeCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
    {
    await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
    await stream.FlushAsync(); // 2. Do I even need this?
    }

    byte buffer = new byte[1024];
    StringBuilder builder = new StringBuilder();
    int bytesRead = 0;

    using (var readCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
    {
    while (stream.DataAvailable)
    {
    bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, readCts.Token);
    builder.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
    }
    }

    string msg = receivedMessage.ToString();
    }

    return ParseMessageIntoList(msg); // parses message into IList<MyModel>
    }
    catch (OperationCancelledException ex1)
    {
    // 3. If 10 second timeout expires, I expect to hit this catch block but I dont see it happen?
    Debug.WriteLine(ex.Message);
    }
    catch (Exception ex2)
    {
    // Catch any other exception and return empty list
    return await Task.FromResult<IList<MyModel>>(new List<MyModel>());
    }
    }









    share|improve this question







    New contributor




    cd491415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      1












      1








      1





      $begingroup$


      I am very new to Tasks and therefore new to handling task cancellations and task exceptions.



      I wrote this method that gets a List which is then used to populate an ObsservableCollection shown in a ListView but I am not sure if I am handling cancellations and exceptions properly.



      I would like to cancel awaited tasks if they dont execute successfuly within 10 seconds time frame. In addition, I would like to handle any exceptions and to properly release any resources, hence I am using the "using" statements below.



      public override async Task<IList<MyModel>> GetDataAsync(string Id)
      {
      try
      {
      // 1. Connecting TcpClient may take up to 90sec? How to time that to 10sec?
      using (TcpClient client = new TcpClient(ip, port))
      using (NetworkStream stream = client.GetStream())
      {
      byte messageBytes = GetMessageBytes(Id);

      using (var writeCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
      {
      await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
      await stream.FlushAsync(); // 2. Do I even need this?
      }

      byte buffer = new byte[1024];
      StringBuilder builder = new StringBuilder();
      int bytesRead = 0;

      using (var readCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
      {
      while (stream.DataAvailable)
      {
      bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, readCts.Token);
      builder.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
      }
      }

      string msg = receivedMessage.ToString();
      }

      return ParseMessageIntoList(msg); // parses message into IList<MyModel>
      }
      catch (OperationCancelledException ex1)
      {
      // 3. If 10 second timeout expires, I expect to hit this catch block but I dont see it happen?
      Debug.WriteLine(ex.Message);
      }
      catch (Exception ex2)
      {
      // Catch any other exception and return empty list
      return await Task.FromResult<IList<MyModel>>(new List<MyModel>());
      }
      }









      share|improve this question







      New contributor




      cd491415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I am very new to Tasks and therefore new to handling task cancellations and task exceptions.



      I wrote this method that gets a List which is then used to populate an ObsservableCollection shown in a ListView but I am not sure if I am handling cancellations and exceptions properly.



      I would like to cancel awaited tasks if they dont execute successfuly within 10 seconds time frame. In addition, I would like to handle any exceptions and to properly release any resources, hence I am using the "using" statements below.



      public override async Task<IList<MyModel>> GetDataAsync(string Id)
      {
      try
      {
      // 1. Connecting TcpClient may take up to 90sec? How to time that to 10sec?
      using (TcpClient client = new TcpClient(ip, port))
      using (NetworkStream stream = client.GetStream())
      {
      byte messageBytes = GetMessageBytes(Id);

      using (var writeCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
      {
      await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
      await stream.FlushAsync(); // 2. Do I even need this?
      }

      byte buffer = new byte[1024];
      StringBuilder builder = new StringBuilder();
      int bytesRead = 0;

      using (var readCts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
      {
      while (stream.DataAvailable)
      {
      bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, readCts.Token);
      builder.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
      }
      }

      string msg = receivedMessage.ToString();
      }

      return ParseMessageIntoList(msg); // parses message into IList<MyModel>
      }
      catch (OperationCancelledException ex1)
      {
      // 3. If 10 second timeout expires, I expect to hit this catch block but I dont see it happen?
      Debug.WriteLine(ex.Message);
      }
      catch (Exception ex2)
      {
      // Catch any other exception and return empty list
      return await Task.FromResult<IList<MyModel>>(new List<MyModel>());
      }
      }






      c# error-handling asynchronous tcp xamarin






      share|improve this question







      New contributor




      cd491415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      cd491415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      cd491415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 2 hours ago









      cd491415cd491415

      1061




      1061




      New contributor




      cd491415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      cd491415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      cd491415 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          Try this. I think it should throw as you expect.



          using (var writeCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10)))
          {
          writeCts.Token.ThrowIfCancellationRequested();
          await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
          await stream.FlushAsync(); // 2. Do I even need this? I think so. This ensures it has finished writing to the actual hardware.
          }


          see here for how to set a connect timeout on your tcpclient



          https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient






          share|improve this answer










          New contributor




          justjoshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            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: "196"
            };
            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: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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
            });


            }
            });






            cd491415 is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214429%2fc-handling-task-cancellations-timeouts-and-exceptions%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0












            $begingroup$

            Try this. I think it should throw as you expect.



            using (var writeCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10)))
            {
            writeCts.Token.ThrowIfCancellationRequested();
            await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
            await stream.FlushAsync(); // 2. Do I even need this? I think so. This ensures it has finished writing to the actual hardware.
            }


            see here for how to set a connect timeout on your tcpclient



            https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient






            share|improve this answer










            New contributor




            justjoshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






            $endgroup$


















              0












              $begingroup$

              Try this. I think it should throw as you expect.



              using (var writeCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10)))
              {
              writeCts.Token.ThrowIfCancellationRequested();
              await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
              await stream.FlushAsync(); // 2. Do I even need this? I think so. This ensures it has finished writing to the actual hardware.
              }


              see here for how to set a connect timeout on your tcpclient



              https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient






              share|improve this answer










              New contributor




              justjoshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






              $endgroup$
















                0












                0








                0





                $begingroup$

                Try this. I think it should throw as you expect.



                using (var writeCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10)))
                {
                writeCts.Token.ThrowIfCancellationRequested();
                await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
                await stream.FlushAsync(); // 2. Do I even need this? I think so. This ensures it has finished writing to the actual hardware.
                }


                see here for how to set a connect timeout on your tcpclient



                https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient






                share|improve this answer










                New contributor




                justjoshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                $endgroup$



                Try this. I think it should throw as you expect.



                using (var writeCts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(10)))
                {
                writeCts.Token.ThrowIfCancellationRequested();
                await stream.WriteAsync(messageBytes, 0, messageBytes.Length, writeCts.Token);
                await stream.FlushAsync(); // 2. Do I even need this? I think so. This ensures it has finished writing to the actual hardware.
                }


                see here for how to set a connect timeout on your tcpclient



                https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient







                share|improve this answer










                New contributor




                justjoshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                share|improve this answer



                share|improve this answer








                edited 53 mins ago





















                New contributor




                justjoshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                answered 1 hour ago









                justjoshinjustjoshin

                12




                12




                New contributor




                justjoshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                New contributor





                justjoshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                justjoshin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






















                    cd491415 is a new contributor. Be nice, and check out our Code of Conduct.










                    draft saved

                    draft discarded


















                    cd491415 is a new contributor. Be nice, and check out our Code of Conduct.













                    cd491415 is a new contributor. Be nice, and check out our Code of Conduct.












                    cd491415 is a new contributor. Be nice, and check out our Code of Conduct.
















                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • 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.


                    Use MathJax to format equations. MathJax reference.


                    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%2fcodereview.stackexchange.com%2fquestions%2f214429%2fc-handling-task-cancellations-timeouts-and-exceptions%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

                    How to make a Squid Proxy server?

                    第一次世界大戦

                    Touch on Surface Book