locked
C#: try/catch for Thread.Sleep RRS feed

  • Question

  • Hello

    I have this code:

                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        Thread.Sleep(3000);
                    }
                    catch(Exception ex)
                    {
                    }
                })
                .ContinueWith((prevTask) =>
                {
                    wmpImageFiles.Ctlcontrols.pause();
                }, TaskScheduler.FromCurrentSynchronizationContext());


    I change this code:

                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        Thread.Sleep(3000);
                    }
                    catch(Exception ex)
                    {
                        using (StreamWriter sw = new StreamWriter(Application.StartupPath + @"\log.txt", true, UTF8Encoding.UTF8))
                            sw.Write(DateTime.Now.ToString() + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + "/////////////////" + Environment.NewLine);
                    }
                })
                .ContinueWith((prevTask) =>
                {
                    wmpImageFiles.Ctlcontrols.pause();
                }, TaskScheduler.FromCurrentSynchronizationContext());

    Is it good?

    I do not want a user to face to messages.

    With Thanks


    • Edited by ARZARE Monday, December 21, 2015 2:07 PM
    Monday, December 21, 2015 2:06 PM

Answers

All replies

  • You should not use empty catch blocks just to ignore exceptions. This is a bad practice. You could catch the exception and do some logging inside the catch clause though. That's better. But you may want to throw the application again once you have logged it:

    try
                    {
                        ...
    } catch(Exception ex) { //log.... throw; }

    Because, in general, you should only catch known exceptions that can actually be handled and lead to a stable state of your application. Catching exceptions just for the sake of prevening an error message to pop up is not a very good idea. The application crashing is not really the worst thing than can happen, ignoring exceptions and pretending that they never happened may be much worse and leave your application in an invalid or unknown state.

    In this particular case, you are not likely to end up in the catch clause at all though since the Sleep method won't throw any exception.


    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

    Monday, December 21, 2015 2:18 PM
  • Why have you got a try catch block on a sleep statement at all?

    I don't really see how this:

    Thread.Sleep(3000);

    Is possibly going to give an error you're not going to see the first time you spin it up to test.

    .

    In any case.

    I suggest you instead consider async await for whatever you're trying to do there.

    Mark whatever method that'll be called from async and you can do.

            async private void DoWhatever()
            {
                await Task.Delay(3000);
                ...
                // Your delayed code here
            }

    And you could make that an async task which returns a value rather than a void in order to run the code on a different thread.

    Read up on async await.

     


    Hope that helps.

    Technet articles: WPF: Layout Lab; All my Technet Articles

    Monday, December 21, 2015 3:30 PM
  • i don't think avoid user to face message is good practice

    imaging that , if a user run your program and meet a exception, but user could not get any response, no people would happy.

    my approach is catch the all known exception at top UI level and show message to user.

    of course, there are something would be remind

    1.if task is a batch work which would process work item in a loop and each work item is independent, it's better to collect all exception in the catch and rethrow a composite exception, like below

    MyCompositeException _ce = null; foreach (var item in collection) { try { ///process item } catch (ApplicationException _ex) {

    //log.... if (_ce == null) _ce = new MyCompositeException(); _ce.AddException(_ex); } } if (_ce != null) throw _ce;

    2. if task run ad server asynchronously, you might not only log the exception but also response to user by somehow (e.g, email, or other message function)


    DON'T TRY SO HARD,THE BEST THINGS COME WHEN YOU LEAST EXPECT THEM TO.

    Tuesday, December 22, 2015 1:59 AM
  • Hello

    Thank you very much Magnus, Andy ONeill and Matthew LEAN . D

    I had saw an exception from my code but I did not remember the name of the exception.

    Correct recognition of usage of exceptions is hard for me.

    Tuesday, December 22, 2015 11:29 AM
  • Hello

    Thank you very much Magnus, Andy ONeill and Matthew LEAN . D

    I had saw an exception from my code but I did not remember the name of the exception.

    Correct recognition of usage of exceptions is hard for me.

          i think exception handling is troublesome for everyone...but stability of application need them..

       it's seem there has a c# extension would help this work ,

       http://www.postsharp.net/

      i am studying now...:)


    DON'T TRY SO HARD,THE BEST THINGS COME WHEN YOU LEAST EXPECT THEM TO.

    Tuesday, December 22, 2015 11:49 AM
  • Wednesday, December 23, 2015 11:18 AM