Start timer from another thread

I am working on a project which will receive command from telnet and start a timer.
In the sock function, I use form reference to call timer.start(), but timer control cannot start Tick event:
Here is code for sock functin after receive the command:
 static void appServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
            switch (requestInfo.Key.ToUpper())
                case ("START"):
                    session.Send(requestInfo.Body);
                    changetimer(1, requestInfo.Body);
break;}}
Here is the function to call timer start:
  static void changetimer(int action, string incomingmsg)
            //timer1.Start();
            Form1 frm = (Form1)Application.OpenForms["form1"];
            switch (action)
                case 1:
                     frm.timer1.Start();
                     break;
                case 2:
                    frm.timer1.Stop();
                    break;
and this is timer tick :
private void timer1_Tick(object sender, EventArgs e)
            TimeSpan result = TimeSpan.FromSeconds(second);
            string fromTimeString = result.ToString();
            label1.Text = fromTimeString;
            second = second + 1;

You should start the timer on the UI thread. You could use the Invoke method to access a UI element from another thread:
static void changetimer(int action, string incomingmsg)
//timer1.Start();
Form1 frm = (Form1)Application.OpenForms["form1"];
switch (action)
case 1:
frm.Invoke(new Action(() => { frm.timer1.Start(); }));
break;
case 2:
frm.Invoke(new Action(() => { frm.timer1.Stop(); }));
break;
Hope that helps.
Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

Similar Messages

  • Can i catch an exception from another thread?

    hi,guys,i have some code like this:
    public static void main(String[] args) {
    TimeoutThread time = new TimeoutThread(100,new TimeOutException("超时"));
    try{
    t.start();
    }catch(Exception e){
    System.out.println("eeeeeeeeeee");
    TimeoutThread will throws an exception when it runs ,but now i can't get "eeeeeeeeeee" from my console when i runs the main bolck code.
    i asked this question in concurrent forums,somebody told me that i can't.so ,i think if i can do this from aspect of jvm.
    thank you for your help
    Edited by: Darryl Burke -- Double post of how to catching exceptions from another thread locking

    user5449747 wrote:
    so ,i think if i can do this from aspect of jvm. What does that mean? You think you'll get a different answer in a different forum?
    You can't catch exceptions from another thread. It's that easy. You could somehow ensure that exceptions from that other thread are always caught and somehow passed to your thread, but that would be a different thing (you would still be catching the exception on the thread it is originating from, as is the only way).
    For example you can use setUncaughtExceptionHandler() on your thread to provide an object that handles an uncaught exceptions (and you could pass that uncaught exception to your other thread in some way).

  • How to refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

  • Killing an exec'ed process from another thread

    Hi all,
    I written an application that executes some external OS - processes. There is a dispatcher thread, that starts the execution threads for some jobs. Every execution thread creates a Processes by calling runtime.exec(), adds this object to a TreeMap ( member of the dispatcher ), creates two threads for reading the output of the process ( sdtout & stderr ) and calls p.waitFor(). From this moment this thread is blocked. After the process is done, the results will be processed by this thread etc. Now I want to go ahead and let the application user kill the process. For them I let the dispatcher - thread, that has also a reference to the executed process to call destroy of it if necessary during the execution thread is blocked by waitFor() and two output threads are reading stdout & stderr. The problem is however that destroy() - call from another thread doesn't kill the subprocess. The subprocess is running until it's done or terminated from out of jvm. Have you an idea or example?
    Thanks a lot & regards
    Alex

    >
    I know you have been discussing your problem is that
    you can't kill a "sleep" process. But just to be
    sure, I tested your description by one thread exec-ing
    a "not-sleep" program, and then another thread had no
    trouble killing it.
    I took your code and wrote a program around it such
    that
    Thread1 :
    - creates a Job (but not a "sleep" job); creates a
    JobMap ; puts Job in JobMap
    - starts Thread2 (passing it JobMap)
    - sleeps 15 seconds
    - calls Job.kill() (your method)
    Thread2 :
    - gets Job from JobMap
    - calls Job.execute() (your method)
    It's quick and dirty and sloppy, but it works. The
    result is when the kill takes place, the execute
    method (Thread2) wakes from its waitFor, and gets
    exitValue() = 1 for the Process.
    so,
    In order to kill the sleep process, which (according
    to BIJ) is not the Process that you have from exec
    call, maybe the only way to kill it is to get its PID
    an exec a "kill -9" on it, same as you said you had to
    do from the commandline. I don't know if you can get
    the PID, maybe you can get the exec-ed process to spit
    it onto stdout or stderr?
    (I am on win, not *nix, right now, so I am just
    throwing out a suggestion before bowing out of this
    discussion.)
    /MelHi Mel,
    yes, it should work right on windows because you created probably the shell by cmd /c or something like this. If you kill the cmd - process, everithing executed by the interpretter will be killed too. My application is running on Windows and unix. On unix I have to execute the process from a shell ( in my case it is the born shell ). The problem is however, that the born shell has another behaviour as cmd and doesn't die. Do you have an idea how to get the pid of the process started by sh without command line? To kill the processes from the command line is exactly what my customers do now. But they want to get "a better service" ...:-)
    Regards
    Alex

  • Starting up from another computers hard drive

    How do start up from another computers hard drive? I'm having trouble with my iMac g5's drive and need to see it on the desktop of my powerbook so I can back up data from it before I erase it.
    Thanks.

    How do start up from another computers hard drive?
    I'm having trouble with my iMac g5's drive and need
    to see it on the desktop of my powerbook so I can
    back up data from it before I erase it.
    Thanks.
    You don't need to start up your mac from another computer's hard drive to see it on the desktop of your powerbook.
    Startup your iMac in target disk mode and then connect it to your powerbook with a firewire cable and it should mount on the powerbook's desktop.
    see How to use FireWire target disk mode

  • Catching an exception thrown from another thread

    I have a SocketServer that creates new threads to handle incoming clients. If one of the threads throw a SQLException is it possible to catch that exception in the SocketServer that created that thread.
    I tried implementing this code and I cannot get the server to catch an exception thrown in the thread. Are my assumptions correct?
    I was reading something about Thread Groups and implementing an uncoughtException() method, but this looked like overkill.
    Thanks for your time!
    Some Example code would be the following where the ClientThread will do a database query which could cause an SQLException. I'd like to catch that exception in my Socket Server
          try
                 new ClientThread( socketServer.accept() , host, connection ).start();
          catch( SQLException e )
                 System.out.println( "DataSource Connection Problem" );
                  e.printStackTrace();
          }

    hehe, why?
    The server's job is to listen for an incoming message from a client and pass it off to a thread to handle the client. Otherwise the server will have to block on that incoming port untill it has finished handling the client and usually there are many incoming clients continuously.
    The reason I would want to catch an exception in the server based on the SQLException thrown in the thread is because the SQLException is usually going to be due to the fact the datasource connection has become unavalable, or needs to be refreshed. This datasource connection is a private variable stored in the socket server. The SocketServer now needs to know that it has to refresh that datasource connection. I would normally try to use somesort of flag to set the variable but to throw another wrench into my dilemma, the SocketServer is actually its own thread. So I can't make any of these variables static, which means I can't have the thread call a method on teh socket server to change the status flag. :)
    I guess I need implement some sort of Listener that the thread can notify when a datasource connection goes down?
    Thanks for the help so far, I figured java would not want one thread to catch another thread's exceptions, but I just wanted to make sure.

  • Trying to update UI with from another thread

    Hi,
    I start a JavaFX application from another class, and then I want to modify UI components from it. I have been trying to use Platform.runLater to do it.
    But the GUI hangs initially (doesnt display anything) for the first 5 seconds (sleep time) and then modifies and shows it.
    I want to display the GUI at first, and then after 5 seconds the GUI should update with the message, but with the below code it just hangs first and displays everything after 5seconds.
    Here sampleGUI is a a javafx app with text fields in it.
    +public class StartGame extends Application {+
    +@Override+
    +public void start(Stage stage) throws Exception {+
    final sampleGUI gui = new sampeGUI();
    gui.start(stage);
    +Platform.runLater(new Runnable() {+
    +@Override+
    +public void run() {+
    +try {+
    System.out.println("Sleeping now...");
    Thread.sleep(5000);
    System.out.println("Sleep over!");
    gui.updateText("New message");
    +} catch (InterruptedException ex) {+
    System.out.println("exception" ex);+
    +}+
    +}+
    +});+
    +}+
    +}+

    Platform.runLater(new Runnable() {
      @Override
      public void run() {
    });causes the Runnable's run method to be executed on the FX Application Thread. Since you put Thread.sleep(5000) inside your Runnable's run method, the sleep happens on the FX Application Thread.
    The call to runLater(...) can be invoked from any thread, including the FX Application Thread.
    So if you are not in the FX Application thread, you want to do:
    // any long-running task, for example
    System.out.println("Sleeping now");
    Thread.sleep(5000);
    System.out.println("Sleep over");
    Platform.runLater(new Runnable() {
      @Override
      public void run() {
        // update UI:
        gui.updateText("New Message");
    });If you are on the FX Application thread, which is the case in your Application.start(...) method, you need to create a new thread to execute your long-running code. You can do this "by hand", creating a Thread and a Runnable for it to execute, but it's probably better to use the JavaFX concurrency API, which has lots of useful hooks for updating the UI on the FX Application Thread.
    In this case, the code would look like this:
    public class StartGame extends Application {
      @Override
      public void start(Stage stage) throws Exception {
        final SampleGUI gui = new SampleGUI();
        gui.start();
        final Task<String> waitingTask = new Task<String>() {
          @Override
          public String call() throws Exception {
            System.out.println("Sleeping");
            Thread.sleep(5000);
            System.out.println("Sleep over!");
            return "New Message" ;
        waitingTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
          @Override
          public void handle(WorkerStateEvent event) {
            gui.updateMessage(waitingTask.getValue());
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(waitingTask);
    }There are (probably dozens of) other ways to use a Task to do this. See the [url http://docs.oracle.com/javafx/2/api/javafx/concurrent/Task.html]API docs for Task for more.

  • Shutting down a panel in one thread from another thread.

    For various reasons, I have a program with two threads (actually more than two, but only two are concerned here). One is the main panel that runs at startup, another is a Virtual O'Scope panel with a real-time display. Everything works more or less well, until it's time to exit the program.
    The main program starts by calling a routine to display the VO'scope; this routine calls CmtScheduleThreadPoolFunctionAdv to schedule the VOscope thread with the function VOscopePanelMain.
    VOscopePanelMain initializes things, displays the VOscope panel, and then calls RunUserInterface(); to process events in the VOscope panel.
    When it comes time to close the window, closing the panel (the X box in the upper right corner) triggers the panel callback CB_VoscopePanel, which processes the EVENT_CLOSE: event by calling QuitUserInterface(0); which, in turn, causes RunUserInterface to return to VOscopePanelMain, which then shuts things down, closes the panel properly, and exits. So far so good.
    int CVICALLBACK CB_VoscopePanel (int panel, int event, void *callbackData,
            int eventData1, int eventData2)
        int    iPanelHeight, iPanelWidth, iV2ControlLeft, iV2ControlWidth, iWidth,
            iT2ControlTop, iT2ControlHeight, iHeight, iLeft, iGap, iScreenTop, iScreenLeft,
            iTop, iBoxWidth;
        switch (event) {
            break;
        case EVENT_GOT_FOCUS: //happens when first displayed or refreshed
        case EVENT_PANEL_SIZE: //size the controls on the panel
           ... do stuff here;
            break;
        case EVENT_CLOSE:
            QuitUserInterface(0);  //stop VOscopePanelMain, which in turn closes the panel and cleans stuff up.
            break;
        return 0;
    However, I also want the panel to stop when I close the main program. The only way that I know how to do this cleanly is to have the main program (which has closed all of its panels and is in the process of shutting down) call VOSCOPE_Close_VOScope () which, in turn, calls CallPanelCallback (iHandle_VOscope, EVENT_CLOSE, 0, 0, 0); (which forces a call to CB_VoscopePanel above with the EVENT_CLOSE event), which should call QuitUserInterface, which should cause the RunUserInterface in VOscopePanelMain to return and let it continue to shut down. In addition, after calling CallPanelCallback, the shutdown routine calls CmtWaitForThreadPoolFunctionCompletion to wait for the VOscopePanelMain thread to actually quit and clean up before proceeding.
    But, of course, it doesn't since, and it took me a while to realize this. The call to QuitUserInterface isn't coming from inside of the VOscopePanelMain thread, it's coming from the main panel's thread - which is already in the process of shutting down. So, the main panel thread is telling itself to quit, VOscopePanelMain never gets the QuitUserInterface message, and things stall.
    So: how do I have one thread tell a panel in another thread to cleanly close? Or do I have to get complicated and either replace RunUserInterface in VOscopePanelMain with a loop that processes events manually and looks for a flag, or figure out something with a thread-safe queue? Any help appreciated.
    Attachments:
    Voscope.c ‏76 KB

    Sorry for delay in answering, it took me a while to find time to build up a working example.
    The attached program spawns a thread in a new thread pool and permit you to choose whether to close it from the main thread or the spawned thread itself.
    It appears that in such a minimal configuration the process works as expected. There may be some different configuration in your actual program that prevents this.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?
    Attachments:
    ThreadPoolWithGUI.zip ‏7 KB

  • Start Addon From another addon

    hi..
    is there any way that i can start one addon (which is installed and is active) from another currently running addon??
    and is there any way that automatically i can start business one and log on to a company??  i can give the id and password or the company and also the database in the code.
    thanks, laks.

    I think you could quite easily control which company you log into when launching B1 by simply amending a registry key.
    Standard B1 client keeps track of the last database you logged into, and by default logs you back into that one the next time you log in.  It seems to keep this info in a binary value in the registry called "Company" that is located in
    "HKEY_CURRENT_USER\Software\SAP\SAP Manage\SAP Business One\LogIN"
    Looks like it is just a simple unicode representation of the company database name that is in the key.
    By amending this registry key before launching SAP Business One.exe, you can control what company it tries to log into.  You can easily try this out with regedit to see how it works.
    There are also other registry entries in the same area covering server, servertype etc.
    John.

  • Keymapping (follow up from another thread)

    To follow up on another thread, I checked out the keymappings and found most of what I was looking for.
    Only a couple of things I miss:
    1. SHIFT + TAB doesn't pull the text back with it if the text is not selected. I am convised most editors do this and I keep find myself trying to do it in JDev and it doesn't work, and then I go in a huff.
    2. Ctrl+K, Ctrl+L to perform a word match forwards or backwards, based purely on text in the document, ie. not syntax/context sensitive. This was one of my most used/most time saved features in Netbeans.

    Hi,
    don't understand what 1) is supposed to do. Can you explain this further? Winword and TextPad behave differently. I tried NetBeans and shift+tab is doing nothing.
    For 2) Is it the same as
    pressing ctrl+f to enter a search string and then continuing with F3 for forward matches and shift+F3 for backward matches? If you select a string before pressing ctrl+f then this string is added to the search list.
    If yes, then you can change the key mapping in Tools-->Preferences --> Accelerators to the keyboard combination you are most familiar with (look for "find").
    Frank

  • How to insert a set of rows at a time from another table

    Hello!
    I have a table1 and table 2 - i want to insert a set of rows at a time from table1 to table 2. Then do a COMMIT. Then continue inserting another set of rows and so on.... say i want to insert into table 2 i million records at a time and then do a commit. then continue with the next 1 million and do a commit and so on..until there are no more records in table 1
    Any ideas please!!!!!!!!!!

    may be this will help
    declare
    cursor c1
    select * from table1
    i_counter binary_integer := 1;
    begin
    for c1_rec in c1
    insert into table2
    values(c1_rec.,..);
    if i_counter = 1000? then
    commit;
    i_counter = 1;
    end if;
    i_counter := i_counter+1;
    end loop
    end;

  • How to get process start time from BI BPM Data Source

    Hi,
    I would like to get the process start time using the VC data source BI_BPM_MY_PROCESSES_DS.
    The return parameter BI_START_TIME_VALUE returns numbers like 1.271.858.563.350,00. This seems to be ms beginning from 1970.
    I tried the following to get the current date/time but it didn't work:
    =DTADD(DATETIME(1970,01,01,00,00),@BI_START_TIME_VALUE,'Z')
    Any idea how to do this?
    Thanks,
    Kevin

    Hi Experts,
    Do you have ideas for this SQL query ?
    Regards.

  • Are you suppose to access UIView from another thread?

    A lot of UI events in my apps take place in another thread. So in my uivewcontroller, it catches a button click for example, it launches a NSThread with some parameter. The reason I decided to use a thread is because if the duration takes long the UI completely locks up. The thread then fetches for some result and access a pointer to a UIView (a UILabel for example) and update it's content.
    Now, is this model correct? I'm running in cases where setting the UILabel.text from the thread sometimes work, sometimes doesnt. I'm not sure how to debug. If I change the thread call to a standard method call (which blocks until results are ready) the text is updated correctly.
    Any hints?

    http://developer.apple.com/documentation/Cocoa/Conceptual/Multithreading/ThreadS afetySummary/chapter950_section2.html

  • IPod Touch 5th Generation won't turn on and the home button is broken, followed the steps from another thread but it's still not working

    I have an iPod Touch 5th Generation with iOS 8.1, my home button is broken and I've been using AssistiveTouch for months now. Today I just locked my iPod and it wouldn't unlock again, it doesn't respond at all, it won't turn on. It was almost fully charged, so it's not the battery. I followed the steps from this thread, but I'm still getting the "USBMuxListenerCreate: No Error" message in CMD Prompt. I bought my iPod abroad and even though I do have the warranty, I've been told at the iStore that it's not valid here, so going to the store isn't really an option. Any ideas how to solve this?

    Sorry, but without a working home button it is not possible to reset or restore your device. You should visit an Authorized Appel Service Provider or Apple Store to get it serviced. The warranty for an iPod is not limited to the country where it has been bought, check here: one-year limited warranty
    Jailbraking the device will void the warranty.
    You can check the warranty status by inserting the serial number on this page: https://selfsolve.apple.com/agreementWarrantyDynamic.do
    A list of Authorized Apple Service Providers can be found here: iPod touch - Contact Us - Apple Support

  • Updating CniNumEdit from another thread

    I get the following Exception,
    First-chance exception in pmdcsimulator.exe (KERNEL32.DLL): 0xE06D7363: Microsoft C++ Exception.
    My call Stack looks as below,
    KERNEL32! 77f1d479()
    MSVCRTD! _CxxThrowException@8 + 57 bytes
    AfxThrowOleDispatchException(unsigned short 0, const char * 0x00433e1c, unsigned int 0) line 1574
    PMDCSIMULATOR! NI::CNiControl::CheckThreadId(void) + 91 bytes
    PMDCSIMULATOR! NI::CNiControl::ValidateControl(void) + 22 bytes
    PMDCSIMULATOR! NI::CNiNumEdit:etValue(double) + 62 bytes
    CPmdcsimulatorDlg::AcquisitionWorkFunction() line 1147
    CPmdcsimulatorDlg::AcqProcessThreadFunction(void * 0x0012f2dc) line 1159
    _AfxThreadEntry(void * 0x0012ec58) line 112 + 13 bytes
    _threadstartex(void * 0x010
    96f80) line 212 + 13 bytes
    KERNEL32! 77f04ede()
    How do I update the control..?

    The UI control classes in Measurement Studio 1.0.1 do not support access from other threads. The next release of Measruement Studio will remedy this problem. Until then, there is an example program that shows how you can use a user message to work around this here: http://zone.ni.com/devzone/devzoneweb.nsf/opendoc?openagent&24C350515009D6A1862569AC0073ACC6&cat=61B119A9F74ADC07862568C50070CE22
    Best Regards,
    Chris Matthews
    Measurement Studio Support Manager

Maybe you are looking for