Alternative to Thread.Sleep in catch?

Is there any other way to make the code wait than using Thread.Sleep in catch, because Thread.Sleep disturbs other objects on my form. Here is what I'm trying to do:
Try{
//do something
catch
// wait 10 seconds
//retry

Timers are a bit of a nuisance what with keeping your form in memory even when you try and dispose the things.
You could push the thing you're doing onto another thread.
Use async await.
You could then use Task.Delay.
A very simplified example:
private async void Button_Click1(object sender, RoutedEventArgs e)
await Task.Delay(2000);
// Do something
Because that's an async method processing returns to the caller when it hits the await.
That then pauses 2 seconds without impinging on your UI thread.
Before the separate thread continues with the code after your await.
You could put your try catch into a method like that and it'd do what you want without a timer.
10 seconds seems a bit of a short time by the way.
Hope that helps.
Recent Technet articles:
Property List Editing ;  
Dynamic XAML

Similar Messages

  • Alternative to Thread.sleep() function

    Dear Experts,
    I am developing an application that requires sleep times on the order of nanoseconds. I tried using the Thread.sleep(long milliseconds, int nanoseconds) function, but I found that the smallest time the function will sleep for is 1 millisecond (i.e sleep(1,0) sleeps for the same amount of time as sleep(0,1)). I am pretty sure that the smallest increment you can set a timer to is one millisecond as well. Are there functions out there that can output nanosecond delays?
    Thanks

    I am developing an application that requires sleep
    ep times on the order of nanosecondsThread.sleep() gives you whatever the OS exposes. If the OS doesn't support sub-millisecond sleep times, then you won't get it.
    More importantly, Thread.sleep() does not guarantee sleep times. If the OS scheduler decides that there are a dozen other processes with higher priority (or a dozen other threads in your process), you may find that you've slept for many milliseconds, maybe even seconds.
    If you want more info, I recall www.javaworld.com having an article on sub-millisecond timing. You might want to check there to see if they say anything about sleep times.

  • What is an alternate to Thread.Sleep()?

    What is an alternate to thread.sleep? The reason being, my action listener won't let me throw exceptions so I need an alternative to thread.sleep, anything?

    watwatacrazy wrote:
    What is an alternate to thread.sleep? The reason being, my action listener won't let me throw exceptions so I need an alternative to thread.sleep, anything?I am in no way condoning this idea, because as mentioned it is a very bad idea.
    However. Not lettiing you throw exceptions is not a reason to not do something. All it means is that you need a catch block. You should review the exceptions part of the Java tutorial found here [_Java Tutorial : Exceptions_|http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]

  • Thread.sleep() issue

    Hi,
    It seems that Thread.sleep is inaccurate :
    Date d1 = new Date();
    try {
         Thread.sleep(200);
    } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    Date d2 = new Date();
    System.out.println(d2.getTime() - d1.getTime());
    I ran this multiple times and it returns me either 187 or 188 either 203 or 204
    Is there any explanation about this ?
    Thank you

    If you read the docs for sleep(), you'll see it says, "Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers." On Windows, the system clock is only accurate to about 10-15 ms.

  • Replace the wait with java embedding thread.sleep() function

    Hi,
    How to replace the wait with java embedding thread.sleep() function. Can anyone help.
    Thanks.

    drag and drop the java embedding component
    include the following code in it.
    try{ 
    Thread.sleep(60000);
    }catch(Exception e)
    --Prasanna                                                                                                                                                                                                                                                                                                                           

  • Confusion using Thread.sleep() method

    I tried it in this program
    class NewThread implements Runnable {
      String name; // name of thread
      Thread t;
      NewThread(String threadname) {
        name = threadname;
        t = new Thread(this, name);
        System.out.println("New thread: " + t);
        t.start(); // Start the thread
      // This is the entry point for thread.
      public void run() {
        try {
          for(int i = 5; i > 0; i--) {
            System.out.println(name + ": " + i);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
          System.out.println(name + "Interrupted");
        System.out.println(name + " exiting.");
    class MultiThreadDemo {
      public static void main(String args[]) {
        new NewThread("One"); // start threads
        new NewThread("Two");
        new NewThread("Three");
        try {
          // wait for other threads to end
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          System.out.println("Main thread Interrupted");
        System.out.println("Main thread exiting.");
    }the output is
    one: 5
    two: 5
    three 5
    delay of 1 second
    one:4
    two: 4
    three: 4
    delay of 1second
    what all i know about sleep() is that it pause the currently executing thread for specified time. hence in above program when first thread runs and prints value 5 then it should get paused for 1 second cause there is Thread.sleep(1000) after println() statement.
    and output should be
    one: 5
    delay of 1 second
    two: 5
    delay of 1 second
    three: 5
    delay of 1 second
    but this is not actually happens. may be i am wrong about Thread.sleep method() or something else.
    would you guys please clear it?
    regards
    san

    Thread.sleep() only sleeps the current thread. As each thread runs concurrently they all print concurrently and all sleep concurrently.

  • Repaint() being delayed by Thread.sleep()

    Hello, I am programming a Memory-like card game, where the user picks cards and if they match they stay flipped over, but if they don't match the cards will be displayed for a second and then flipped back over. However, I am running into a problem when the cards do not match, the game will wait (using Thread.sleep()) and then flip the cards back over. The problem is that the second card picked, that is determined to not be a match, is not showing the face before the cards are returned to the hidden state. I think that it is being flipped twice in a row at the end of the sleep(), therefore never actually displaying the front of the card. I have tried putting repaint() everywhere, and there is one before the sleep(), but it still doesn't seem to work properly. Here is the code for my mouse clicked event. Thanks for any help!
      public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        Card temp = null;
        for (int i = 0; i < 52; i++) {
          temp = cards.getCard(i);
          if (temp.contains(x, y)) {
            if (temp.isFront() == true)
              return;
            temp.swapImg();
            this.repaint();
            if (flipped == null) {
              flipped = temp;
            } else {
              if (temp.getVal() == flipped.getVal()) {
                // we have a pair
              } else {
                // cards don't match.. start over
                try {
                  Thread.sleep(500);
                } catch (InterruptedException ie) {
                  System.out.println("Thread was interrupted!\r\n");
                temp.swapImg();
                flipped.swapImg();
              flipped = null;
            break;
      }

    Don't use Thread.sleep() inside a Listener. You are blocking the EDT which prevents the GUI from repainting itself.
    Use a Swing Timer to schedule the flipping of the cards.

  • Menu and Thread.sleep(5000) or Thread.currentThread.sleep(5000)

    Hi,
    I am using JMenu and switchable JPanels.
    When I click on a MenuItem the follownig code should starts
        cards.add(listenPanel,  "listenPanel");
        cardLayout.show(cards, "listenPanel");
        try{
          Thread.sleep(5000); //in ms
          PlayMP3Thread sound = new PlayMP3Thread("sound/ping.mp3");
        } catch(Exception e) {
          e.printStackTrace();
        }It seems to be what I want to reach, but it does not work the way I want it to.
    I would like the Panel to show right away, then wait 5s and then play the sound.
    BUT what it does is freez the unfolded menu for 5s, then plays the sound and after that it shows the new Plane.
    Can you tell me why this is??

    This might be what you want
    package tjacobs.thread;
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.concurrent.Semaphore;
    import tjacobs.ui.Eyes;
    import tjacobs.ui.util.WindowUtilities;
    public class ThreadForMultipleAnytimeRuns extends Thread {
         private Runnable mRunnable;
         private Semaphore mSemaphore;
         public ThreadForMultipleAnytimeRuns(Runnable arg0) {
              super();
              init(arg0);
         private void init(Runnable r) {
              mRunnable = r;
              mSemaphore = new Semaphore(0);
              setDaemon(true);
         public ThreadForMultipleAnytimeRuns(Runnable arg0, String arg1) {
              super(arg1);
              init(arg0);
         public ThreadForMultipleAnytimeRuns(ThreadGroup arg0, Runnable arg1, String arg2) {
              super(arg0, arg2);
              init(arg1);
         public void run () {
              try {
                   while (!isInterrupted()) {
                        mSemaphore.acquire();
                        mRunnable.run();
              catch (InterruptedException ex) {}
         public void runAgain() {
              mSemaphore.release();
         public void runAgain(int numTimes) {
              mSemaphore.release(numTimes);
         public void stopThread() {
              interrupt();
         public int getSemaphoreCount() {
              return mSemaphore.availablePermits();
         public Runnable getRunnable() {
              return mRunnable;
         //The setRunnable method is simply not safe, and
         //trying to make it safe is going to effect performance
         //Plus I can't really see a gain in being able to set
         //The runnable on one of these threads. Just create
         //a new one!
         public synchronized void setRunnable(Runnable r) {
              if (getSemaphoreCount() > 0) {
                   try {
                        wait();
                   catch (InterruptedException ex) {
                        return;
              mRunnable = r;
         public static void main(String[] args) {
              final Eyes eyes = new Eyes(true);
              //eyes.addMouseMotionListener(eyes);
              Runnable r = new Runnable() {
                   public void run() {
                        eyes.blink();
                        try {
                             Thread.sleep(100);
                        catch(InterruptedException ex) {}
              final ThreadForMultipleAnytimeRuns ar = new ThreadForMultipleAnytimeRuns(r);
              ar.start();
              eyes.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent me) {
                        ar.runAgain();
              eyes.setPreferredSize(new Dimension(60,20));
              WindowUtilities.visualize(eyes);
    //          JFrame jf = new JFrame();
    //          jf.add(eyes);
    //          jf.pack();
    //          jf.setLocation(100,100);
    //          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //          jf.setVisible(true);
    }

  • Update jLabel in between Thread.sleep()'s

    I have multiple Thread.sleep()'s in my code under a jButton actionevent evt.
    In between these, I need to be able to update a jLabel, but for some reason it waits until the last thread.sleep() before it updates the jLabel.
    Any ideas why?
    private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {
       try {
          Thread.sleep(1000);
          jLabel.setText("Change Text To This");
          Thread.sleep(1000);
       } catch (InterruptedException ex) {}
    }So rather than waiting 1000ms, then update label, then wait another 1000ms, it just waits 2000ms, then updates the label
    Please help!
    Thanks

    Edward9 wrote:
    I am new to Java and I just cannot work out the tutorials,Hard luck then.
    the code behind my applet doesn't matter as long as it works,Which it will, of you code it correctly after learning from the tutorials.
    I have spend 6 months on this appletWould have taken much less time to learn to do it correctly.
    and everything worksBy your definition of "works"
    apart from this one problem --> jLabel to update between thread.sleep()'s.Easy when you know how.
    Its all I need to do and my project will be over and I can get away from Java.I have a suggestion: why don't you get away from Java right now, take the failing grade you've earned, and get on with your life. Really.
    Is there absolutely no way it can be done?Already covered above and in previous responses.
    I was told the jLabel will not update until the thread is free to do so, so i will need to look up on multiple threads,No, you need to go through the Swing tutorials.
    i have tried to but none of it makes sense to what i need done.Give up. Now.
    db

  • Timers! System.currentTimeMillis() and Thread.Sleep = ?????

    I've experienced some strange results using timers etc. Can anyone explain this:
    package TestPackage;
    public class Timer {
        public static void main( String args[] ) {
            new Timer();
        /** Creates a new instance of Timer */
        public Timer() {
            while ( true ) {
                long startTime = System.currentTimeMillis();
                try {
                    Thread.sleep(100);
                } catch ( Exception e ) {
                    System.err.println("Trouble sleeping tonight...");
                System.out.println("RunTime=" + (System.currentTimeMillis() - startTime) );
    Output:
    RunTime=109
    RunTime=94
    RunTime=109
    RunTime=94
    RunTime=93
    RunTime=110
    RunTime=94
    How can the run time be less than the sleep time ?!?!?!
    Cheers,
    Rob

    There are a multitude of problems here and all of them are Windows related.
    1) Any difference under 10 milliseconds is purely speculative on the part of the OS
    2) There is a Windows bug whereby calling some Windows API with regards to system time basically causes Windows to fall ill with a concussion, temporary coma followed by confusion. The most common symptom of this particular bug is that repeated calls to this API cause teh system clock to accelerate but the nature of the bug means that a variety of tests and results such as this one may be thrown into confusion.

  • Work manager using thread.sleep or delay doesn't work

    Hi all,
    I used Spring framework and oracle weblogic 10.3 as a container.
    I used workmanager for manage my thread, I already made one thread that managed by workmanager. Fortunately spring provide the delegation class for using workmanager, so I just need to put it on applicationContext.xml.
    But when I put the "while" and TimeUnit for sleep the process on desired delayed time, the deployment process never finished. It seems the deployment process never jump out from while loop for finishing the deployment.
    Why?, As I know using typical thread, there is no issue like this. Should I use another strategy for make it always loop and delay.
    This is my simple code :
    import java.util.concurrent.TimeUnit;
    import org.springframework.core.task.TaskExecutor;
    public class TaskExecutorSample{
         Boolean shutdown = Boolean.FALSE;
         int delay = 8000;
         TimeUnit unit = TimeUnit.SECONDS;
         private class MessageGenerator implements Runnable {
              private String message;
              public MessageGenerator(String message){
                   this.message = message;
              @Override
              public void run() {
                   System.out.println(message);
         private TaskExecutor taskExecutor;
         public TaskExecutorSample(TaskExecutor taskExecutor){
              this.taskExecutor = taskExecutor;
              try {
                   while (shutdown.equals(Boolean.FALSE)){
                        this.printMessage();
                        unit.sleep(delay);
              } catch (Exception e) {
                   System.out.println(e.getMessage());
         public void printMessage() {
              taskExecutor.execute(new MessageGenerator("Print this Messages"));
    Really thanks in advance.
    Regards,
    Kahlil
    Edited by: Kahlil on May 26, 2010 2:38 PM
    Edited by: Kahlil on May 26, 2010 2:42 PM

    Hi,
    i m not sure whether it's an issue with Spring or not. But i tried using Thread.sleep(1000) in a Simple webapplication to see Workmanagers works properly or not. I found that it works extremely great: http://weblogic-wonders.com/weblogic/2010/01/24/workmanager-at-webapplication-level/
    Thanks
    Jay SenSharma

  • Using Thread.sleep()

    When I put Thread.sleep() in my code, the debugger says I need to catch it. How do I do that?

    But in general, you don't want to just smother exceptions like that. It's okay when you're sleeping (or can be) because often if you're interrupted, you want to just ignore it and move on. However, there's more to handling exceptions than just an empty catch block.
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

  • Better than thread.sleep

    Whats a good way to get nice FPS, my images are skipping, not sliding like they should
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.BufferStrategy;
    public class TitleScreen extends JFrame implements Runnable, KeyListener {
    Toolkit tk = Toolkit.getDefaultToolkit();
    MediaTracker mt = new MediaTracker(this);
    Dimension d = tk.getScreenSize();
    BufferStrategy strategy;
    Image Title = tk.getImage("images/TitleScreen/Title.png");
    Image Title2 = tk.getImage("images/TitleScreen/Title2.png");
    Image chris = tk.getImage("images/chris/battle.png");
    Image backbuff, backbuff2;
    Thread t = new Thread(this);
    boolean running;
    int X = getX(1280), Y = getY(600), tX = -500, tY;
    public TitleScreen(){
    setTitle("Title");
         setSize(d.width, d.height);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setVisible(true);
         addKeyListener(this);
         strategy = getBufferStrategy();
         createBufferStrategy(2);
         mt.addImage(chris, 0);
         mt.addImage(Title, 0);
         mt.addImage(Title2, 0);
    try{
    mt.waitForAll();
         }catch(InterruptedException e){}
    t.start();
         draw();
    public void draw(){
    running = true;
    while(running){  
         backbuff = createImage(d.width, d.height);
         Graphics g = strategy.getDrawGraphics();     
         Graphics2D g2 = (Graphics2D)backbuff.getGraphics();     
         g2.setColor(Color.black);
         g2.fillRect(0, 0, d.width, d.height);
         g2.drawImage(Title, tX, 0, d.width, d.height, this);
         g2.drawImage(chris, X, Y, getX(chris.getWidth(this)), getY(chris.getHeight(this)), this );     
         g.drawImage(backbuff, 0, 0, this);
         g.dispose();
         strategy.show();}
    public void run() {
    for(int num = 0; num <= 250; num++){
    try{
    X -= 5;
    if(tX != 0){
              tX += 5;}
              t.sleep(5);
         }catch(InterruptedException e){} }
    int getX(int X){
    return X * d.width / 1280;}
         int getY(int Y){
    return Y * d.height / 1024;}
    public void keyPressed(KeyEvent e){
    if(e.getKeyCode() == KeyEvent.VK_ENTER){
         Title = Title2;}
         if(e.getKeyCode() == KeyEvent.VK_RIGHT){
         X += 1;}
    public void keyReleased(KeyEvent e){}
    public void keyTyped(KeyEvent e){}
    public static void main(String args[]){
    new TitleScreen();}
    any help?

    Thanks, now look at my code:
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.*;
    public class TitleScreen extends JFrame implements KeyListener, Runnable {
    Toolkit tk = Toolkit.getDefaultToolkit();
    MediaTracker mt = new MediaTracker(this);
    Dimension d = tk.getScreenSize();
    Image backbuff;
    Graphics g, g2;
    int X[] = new int[]{0, 550, 1500, 1700, 1900};
    int Y[] = new int[] {0, -300, 0, 0, 0};
    Image sonic_left = tk.getImage("images/sonic_left.png");
    Image sonic_right = tk.getImage("images/sonic_right.png");
    Image fox_left = tk.getImage("images/fox_left.png");
    Image fox_right = tk.getImage("images/fox_right.png");
    Image mario_left = tk.getImage("images/mario_left.png");
    Image mario_right = tk.getImage("images/mario_right.png");
    Image toad_left = tk.getImage("images/toad_left.png");
    Image toad_right = tk.getImage("images/toad_right.png");
    Image Title = tk.getImage("images/TitleScreen/Title.png");
    Thread t = new Thread(this);
    public TitleScreen(){
    setTitle("Title");
         setSize(d.width, d.height);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setVisible(true);     
         addKeyListener(this);     
         mt.addImage(sonic_left, 0);
         mt.addImage(sonic_right, 0);
         mt.addImage(fox_left, 0);
         mt.addImage(fox_right, 0);
         mt.addImage(mario_left, 0);
         mt.addImage(mario_right, 0);
         mt.addImage(toad_left, 0);
         mt.addImage(toad_right, 0);
         mt.addImage(Title, 0);
    try{
    mt.waitForAll();
         }catch(InterruptedException e){}
         t.start();
    public void run(){
    while(true){
    try{
    X[2] -= 5;
    repaint();
    t.sleep(1000/ 100);
    }catch(InterruptedException e ){} }
    public void update(Graphics gtop){
    paint(gtop);}
    public void paint(Graphics gtop){
    if(backbuff == null){
         backbuff = createImage(d.width, d.height);
                   g = backbuff.getGraphics();}
                   g.setColor(Color.black);
                   g.fillRect(0, 0, d.width, d.height);
                   g.drawImage(mario_left, X[2], 795, this);
              gtop.drawImage(backbuff, 0, 0, this);
    int getX(int X){
    return X * d.width / 1280;}
         int getY(int Y){
    return Y * d.height / 1024;}
    public void keyPressed(KeyEvent e){}     
    public void keyReleased(KeyEvent e){}
    public void keyTyped(KeyEvent e){}
    public static void main(String args[]){
    new TitleScreen();}
    The animation is smooth, but it sometimes moves a bit faster and you can see the lines being drawn. I tried the managed image but i didnt understand it and how to use it. But is there something im missing that is making the image jump a bit in its smooth animation?

  • What's wrong to put Thread.sleep in a session bean?

    i am working on a trading platform and i think there is a design flaw. The part i am working on is the Order Management module. When an order value object is published to a JMS topic and picked up by a MDB. The MDB, in turn, calls a session bean (could be stateless, I didn't check), OrderEngineBean. After this bean saves the order vo into database and broadcast the message to all involved parties, it suspends for 12 sec, using Thread.sleep, so other parities might have a chance to update the vo. If no update occurs, the order is considered expired and abandoned.
    It looks awkward to me to use a Thread.sleep in a session, but I haven't come out with a better idea to deal with the scenario like above.
    Anyone can help me out?
    Thanks a lot!
    Sway

    Setting the property "max-beans-in-free-pool" is not the answer to this issue. By setting this property to 1, the container merely instantiates and keeps one instance of the bean in the free pool at the "start" of the app server. But if the container comes across more than one requests for the same EJB simultaneoulsy, then it will create new instances at that time to handle the requests simultaneously.
    You are seeing intermixed log messages between two threads because these messages are being logged from two different instances of the EJB and NOT the same instance of the EJB. The container does synchronizes the calls on "a method" on "a instance". So what you are seeing are the messages coming from "a method" on "two different instances" of the same EJB.
    You can refer to the EJB 2.0 specification section 6.11.6 Non-reentrant instances for details about simultaneous access to the same session object.

  • Problem with Thread.sleep()

    hi all,
    I am trying Thread.sleep() method to introduce a delay. In the program i ask the user to specify the value to be entered in Thread.sleep() (to indicate the amount of delay desired by the user). but strangely, if a low value is entered, i get a different result which actually should not happen as the rest of the calculation remains the same, only the amt of delay changes.
    could anyone help me with this
    cheers
    ankit

    [url http://forum.java.sun.com/thread.jsp?forum=31&thread=536288]Double-post

Maybe you are looking for

  • Os x tiger and asus ?

    A couple of newbie questions: When i do upgrade to a 40gb hd what version of tiger should i shop for? Will the "full retail" version work on my ibook? I've seen "Powerbook" versions on ebay. also, will the asus wl-167g work on this clamshell? thanks

  • Insert PDF CS2

    Trying to get a PDF into a GoLIve page. I can't find the proper object. Can someone tell me how to get a multipage PDF into GL CS2, and have it capable of opening in a browser as a PDF? Thank you.

  • Transfer e-mail addresses from Internet Explorer to Thunderbird

    I have been using Internet Explorer and AT&T for all on-line uses including e-mail. I am admittedly somewhat novice, so I need someone to "walk" me through the process of getting all my e-mail addresses transferred over to Mozilla and Thunderbird. Pl

  • Skype click-to-call isn't being installed during t...

    I got a notification to upgrade my skype so I clicked it and followed the steps but near the end, it said that 'Skype click-to-call' isn't being installed, during the upgrade. What's happening?

  • CRS-0223: Resource has placement error, when starting DB instance

    Hello All, Env: 2 node 10.2.0.4 RAC on Solaris 10 SPARC All of a sudden the DB instance on Node 2 crashed. The alert.log says "Instance terminated by MMAN". There were no changes recently. I tried to start it up using srvctl and it failed with [SHCL1