Timer in separate Thread.

Hi.
In my application i have a timer use to tick after every second and update a lable on UI. problem i was facing was that when time is enable none of the touch event was working.
I googled it and found that i have to call timer function from another thread..
after some effort i manage to run a separate thread. but now i m facing problems in calling a timer function here is the code.
Create Thread
myThread = [[NSThread alloc] initWithTarget:self selector:@selector(SapThread:) object:nil];
[myThread start];
SapThread Function....
- (void)SapThread:(id)info {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSTimer *appTimer = [NSTimer scheduledTimerWithTimeInterval:(1/20) target:self selector:@selector(UpdateTime) userInfo:nil repeats:YES];
[pool release];
UpdateTime Function for timer
-(void) UpdateTime
//set lable value.
problem is this that UpdateTime function never called.
Thankz in advance
Muhammad Usman Aleem

As I tried to explain above, I didn't expect your code to work after you corrected the firing method signature.
Your detached thread doesn't run until you release your myThread object. It terminates when execution reaches the end of your SapThread method. That's why the timer never fires when you run it in that thread.
In any case, I think sptrakesh is absolutely correct. There's no reason a timer in the main thread should prevent you from catching touch events. So I think you have two major points of confusion:
1) Your thread isn't doing anything, since it terminates before the timer ever fires once;
2) You have mis-diagnosed the problem with the touch events and don't need a new thread. I.e. even if you got a detached thread working to fire your timer, that's not going to solve your touch problem.
I think bringing a new thread into the mix has gotten you in over your head and taken your attention away from the primary problem. So take sptrakesh's advice. Put the timer back into the main thread and focus on why you're not catching the events you want.

Similar Messages

  • Modelling time in an separate thread

    Hello, when I run this piece of code in my program it prints out 25 in one second, 50 in the next and so on. Dont know why it does this but what I want is it to go 1 in the first second and 2 in the second second etc etc.
    I thought that if I made it into a separate thread it will work.
    Please in the simplest form can you tell me how to do this.
    Cheers
    public static void time()
                   new javax.swing.Timer(1000, new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             time++;
                             System.out.println(time);
                             //timeArray[time] = time;
                   }).start();
         

    Its too difficult to make a short compilable app but what I can say is that its in:
    static class LocalTableModel extends AbstractTableModel
         public static void algorithm(int totalJobsIn, String[][] processArrayIn)
              new javax.swing.Timer(1000, new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        timer++;
                        System.out.println(timer);
                        //timeArray[time] = time;
              }).start();                         
    }Cheers

  • Cannot Open Form Created on Separate Thread After Closing

    My application communicates with a device that has several sensors.  As the sensors collect data, they send messages over the com port.  I have written a class to communicate with the device.  As the messages come in and are processed, the
    class raises events that the application responds to.
    The main window of the application handles the communication with the device and displays several statistics based on the data collected.  When the user presses a button on the device, a specific event is raised.  The main window create a separate
    thread and opens a child window.  When the child window is open, the user opens a valve to dispense the product.  As the product is dispensed, a flow meter connected to the device measures the volume of product dispensed.  The flow meter generates
    messages to indicate the volume dispensed.  I need to be able to send messages from the main window to the child window so that the child window displays the volume.  When the user is done, they close the valve dispensing the product and press the
    "End" button on the child window.  The child window then updates several variables on the main window, makes a couple of database calls to record how much product was dispensed and by whom and then closes.
    I need to run the child window using a separate thread as both windows need to be able to process commands.  If only one window has control the program doesn't work at all.  I have it figured out so that everything is working.  I can open
    the child window, dispense product, se the amount of product dispensed in the child window (the main window processes commands from the device and updates the label on the child window using a delegate), closes the window (using Me.Close()) and updates the
    main display with the updated data.  The problem is that when a user goes to dispense product a second time, I get the following error:
      A first chance exception of type 'System.ObjectDisposedException' occurred in System.Windows.Forms.dll
      Additional information: Cannot access a disposed object.
    I thought that maybe I could hide the window (change Me.Close() to Me.Hide) and then just show it.  When I do that I get this error:
      A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
      Additional information: Cross-thread operation not valid: Control 'frmPour' accessed from a thread other than the thread it was created on.
    Both of these errors make sense to me, I just can't figure out how to make it work.
    First I have to declare the child window as a global variable as I need to access the window from a couple of the event handlers in the main form.
    Public frmMeasure As New frmPour
    When the user presses the button on the device to dispense the product, the event handler executes this code to open the child window.
    Private Sub StartPour(sAuthName As String, sAuthToken As String, iStatus As Integer) Handles Device.Pour
    Dim th As System.Threading.Thread = New Threading.Thread(AddressOf Me.OpenDispenseWindow)
    th.SetApartmentState(ApartmentState.STA)
    th.Start()
    End If
    End Sub
    Which executes this code:
    Public Sub OpenDispenseWindow()
    frmMeasure.sNameProperty = sCurrentUserName
    frmMeasure.sAuthTokenIDProperty = sUserToken
    Application.Run(frmMeasure)
    bAuthenticated = False
    bPouring = False
    dSessionVolume += GetTapConversion(sCurrentValve) * iFinalTick
    UpdateDisplayDelegate(iValveID)
    End Sub
    It doesn't matter if I use Me.Close() or Me.Hide(), both methods fail on the Application.Run(frmMeasure) line with the errors shown above. 
    For the Me.Close() method, my thinking is that the global frmMeasure object is getting disposed when I close the child window.  Is there any way that I can re-instantiate it when I go to display the window again?
    For the Me.Hide method, is there any way that I can track the thread that created it in the main window and when I go to call it a second time, detect that it is already available and just Show() it?
    Any hints, tips or suggestions are appreciated.
    Thanks.
    John
    John

    To be honest, I have only grasped < 100% of your message in detail, but...: Windows that have a parent<->child relation must be running in the same thread. In addition, after closing a modeless window, you must not use it anymore. Instead, create
    a new instance.
    What happens if you do not create a new thread but instead open the child in the same thread (which is obligatory)? You wrote it doesn't work, but I don't know why?
    "First I have to declare the child window as a global variable".
    How do you define "global"? Normally this is a variable in a Module declared with the scope Public or Friend. But I guess you mean a field of the Form (a variable at class level in the Form).
    "I need to be able to send messages from the main window to the child window so that the child window displays the volume."
    Why does the main window has to send the messages? Can't the child window handle the device's messages itself?
    "I need to run the child window using a separate thread as both windows need to be able to process commands."
    Process commands from the device, or commands from the user operating the Forms?
    Armin

  • Is the main program seen as a separate thread ?

    I wanted to stop a GUI based program opening too fast because the splash screen wasn't seen for long enough.
    So I tried to use the Thread and Runnable classes within the GUI constructor.
    By trying different things, I got it to do as I wanted : a delay of 10 seconds before showing the program's GUI.
    But I don't understand why main is not seen as a separate thread and thus continue to make itself visible no matter what the delayThread status may be.
    // Constructor:
    public Hotel (int numberIn)
             // Create the time delay thread so that users may enjoy the splash !
             delayThread = new Thread(this);
             delayThread.run();
             // Initialise the number of rooms and the GuestList :        
            noOfRooms =  numberIn;
            guests  = new GuestList(noOfRooms);
            // Graphics settings:     
            setTitle("Hotel");     
            setLayout(new FlowLayout());
           // etc. etc.
           // etc. etc.
           setVisible(true);
        // A run method to delay the program opening:
        public void run()
             try
                  delayThread.sleep(10000);
             catch(InterruptedException ie)
                  ie.printStackTrace();
        }Now, maybe a better way to do this would be to move the setVisible statement from the constructor to the run method.
    Maybe there is an even better mechanism for producing a delay in a program's opening.
    But I'm still curious as to why the main thread was delayed by a delay in what is really an entirely separate thread.
    Any ideas ?
    Edited by: KonTiki on 16-Feb-2013 13:10
    Edited by: KonTiki on 16-Feb-2013 13:19
    Edited by: KonTiki on 16-Feb-2013 13:20
    Edited by: KonTiki on 16-Feb-2013 13:21
    Edited by: KonTiki on 17-Feb-2013 09:16

    Well, first of all calling a Thread object's run() method just runs the code in the same thread. It doesn't start a new thread -- that's what calling the start() method does.
    And the Thread.sleep() method is a static method, meaning "Make *this* thread sleep for X milliseconds". So calling it on another Thread object doesn't cause that thread to sleep, it causes the current thread to sleep.
    I suggest you should go through the concurrency tutorial from Oracle because you seem to be programming by guesswork here.

  • Trouble with TestStand running VB DLLs compiles in separate threads

    I have an application that uses DLLs written in VB 6 to manipulate hardware. The hardware is Stepper Motors controlled via the NI CAN bus card, and two instruments controlled via the GPIB PCI card. I have written the two DLLs to use the same NI PCI GPIB and the same NI CAN BUS card. (One instrument per DLL and One Motor per DLL)
    Test stand is then creating the DLLs and running them in separate threads. I have the one DLL Call in a subsequence running as a separate thread, and the other DLL is in the main sequence. I have a GOTO step with preconditions set so that the main sequence only continues after the separate thread in the subsequence is finished.
    The problem I am having is that these D
    LLs work OK when I run them both in the VB debugger. The program even works when I run the main thread in the debugger, and the subsequence is run compiled.
    The problem is, that if I try to run both of these DLLs compiled It seems as if the subsequence DLL never executes.

    To Tuxamation -
    Nothing comes to mind as to why this would happen. VB 6 automation DLLs are used all the time for code modules.
    Note that when MSVB debugs a DLL, it is actually running the DLL as an EXE server within the MSVB process and not in TestStand's process that is using it. I typically found that there is typically a subtle difference in behavior between running the server as an EXE or DLL server.
    A simple way to determine if the TestStand call is reaching your DLL is to place a MsgBox function call in the DLL entry point and immediately return, ie. bybassing your existing code.
    So, if the call is being made to your DLL, you could then enable the Visual Basic project option on the Compile tab, "Create Symbol Debug Info" and recreate your VB DLL.
    You can then attach Microsoft Visual Studio (C++ debugger) to the TestStand process, open the file that contains the entry point in to DLL that TestStand calls, set a breakpoint, and see if the breakpoint is reached.
    Scott Richardson
    Scott Richardson
    National Instruments

  • Separate thread to monitor PXI-6115

    I am using a PXI-6115 multifunction analog I/O card to monitor a power supply to assure regulation. I am monitoring 4 different points with a resolution of 1000S/s each. I would like to check each point and determine whether it is withing an acceptable window of operation both above and below the voltage it is supposed to be operating at. If it is out of regulation for a specified period of time, I want to write a chunk of the waveform to a spreadsheet file for analysis.
    I have been able to successfully complete a majority of this. The only problem is that I want all of this to happen in the background so that I can also execute numerous other vi's to change various parameters, etc. in order to stress the supply. However, I run
    into problems in that some of the voltage levels are customizeable and therefore the thresholds must be changed in order to check the new voltage for regulation. When I change these thresholds, they change immediately, however the ni-daq "read" vi is sometimes a couple seconds behind. So... I am comparing the old voltages with the new thresholds and it tells me that my supply is out of regulation when it is functioning correctly, I am simply looking at old data.
    My question is...
    Is multithreading this somehow the best solution to this problem? Should I create a separate thread for my supply monitoring vi and give it a higher priority than my test thread in order to service the AI Read vi often enough to keep the buffer caught up and always be reading current data, or is there a non-buffered AI vi that will work better for this situation. Or am I simply asking too much to have it read 4000 S/s and make comparisons and log data all in the background while doing other stuff?

    I am currently revising my comparison algorithm to try to make it a little more efficient, but I still think that devoting more processor time to this is the solution being that this is time critical while the controlling of the different variables and such in the foreground is not necesarily a high priority. All I am doing is a simple greater than or less than comparison on each element returned from the read and using a bounded count on whether or not it is "in bounds" if it is out of bounds long enough for the bounded counter to go beyond the user specified value, the input for that second is appended to an array that will later be written to a spreadsheet for analysis. It is nothing too elaborate, however, being that it will be executed up to 4000 time
    s per second potentially, it will require some attention from the processor. I am looking for any way to assure that my routine gets executed often enough, preferably to totally empty the buffer once per second.

  • Having 2 objects running in separate threads

    I am accessing cobol programs using the microfocus runtime for java. The problem with it is that a you can only run one instance of a cobol program at the same time, unless they are in separate threads.
    Example:
    CobolTextSearch cobol1 = new CobolTextSearch();
    CobolTextSearch cobol2 = new CobolTextSearch();
    cobol1.execute("FAMILY");
    cobol2.execute("HISTORY");
    System.out.println(cobol1.getRecord());
    System.out.println(cobol2.getRecord());The output of this program results in HISTORY for cobol1 and HISTORY for cobol2. Where as if they were run in separate threads, I would have got FAMILY for cobol1.
    So my question is, is there any way I can run these two objects in separate threads so that any time I access the object it will be in its own thread? I cant just run them in separate threads on the execute because each getRecord is interfacing with cobol. After execute I want to be able to read values from the cobol files to see if they match without having to read each record into memory on the java side.

    No you are not missing anything, you just create a new thread each time you run something or you have to make a setter method to accept parameters for the next run and then a seperate method to actually make your routine execute.
    public void setTask(String s){
      task2Execute = s; //task2Execute is global to the methods
    public boolean runTask(){
      CobolTextSearch cobol = new CobolTextSearch();
      cobol1.execute(task2Execute);
    //  other logic
    }Here is what the docs say about threads: A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

  • Running in separate thread??

    Hi
    I have a code which generates a pdf file. What i wan is for it to run in a separate thread. The filling and creation of the pdf file should be running while i am doing other stuffs.. just like in downloading. the user can browse or do other things in the mean time while waiting.. when the pdf file is ready to be viewed, then the program should interupt whatever the user is doing and pop up a pdf viewer to display the file.
    Is there any way to call the pdf viewer in my code? And how should i do the interrupt? Plus, how do i specify that the pdf creation should run in a separate thread?
    thanks in advance.
    tbozu

    alright, handling the interrupt is highly dependant on the rest of your application, so I won't touch that one, but.
    To create your file in a different thread, wrap the method in it's own thread, so it would look similar to
    new Thread() {
    public void run() {
    writeMyFile(); // your method here
    }.start();then, to start the pdf viewer, try using the Runtime.exec() utilities.
    good luck to you!

  • How do I make a JSlider update my canvas with a separate thread?

    I want to have the option to update my canvas slowly (Thread.sleep commands), so I need a separate thread to do this.
    My problem is: I want the slider to make the canvas update continuously as the user moves the slider, but right now, I'm ending up with countless new threads being created...
    How do I:
    1) keep it at only one separate thread that controls redrawing, and
    2) make it stop when the user moves the slider farther
    Also, if I call MyCanvas.repaint(), which is the canvas class in my program, but outside the RepaintThread,
    will this cause my main thead to sleep?

    To get better help sooner, post a SSCCE that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    From your problem description, a solution may be to use javax.swing.Timer and SwingWorker.
    The Java Tutorials: [Worker Threads and SwingWorker|http://java.sun.com/docs/books/tutorial/uiswing/concurrency/worker.html]
    db

  • How to create a JTree in a separate thread?

    Hi. I am writing a Swing application which has a JTree that is made up of company parent nodes and employee child nodes. My problem is that the data for this JTree is loaded from the database and this process takes a long time making the loading time of the app too slow. I think that this process should probably be done in a separate thread. This would let the gui load much quicker and then when the thread finishes it can update the graphics to display the JTree. I have the code for the JTree all done and it works but I need help on putting it in a separate thread and running the thread. I am having trouble with this. Any help would be greatly appreciated.
    Eugene P.

    Thank you for responding to my question but I actually figured out a solution already. I used the SwingWorker class. When the program loads I just display a simple JTree with just the names of the companies without the employees. This takes almost no time to load. Then in the construct() method of the SwingWorker class I run the query to get the employee names and then create the new JTree that has the firms and the employees. In the finished() method of the SwingWorker class I update the gui. This whole process is running in a separate thread while the gui is already loaded so it works beautifully.

  • Now a separate thread for the HTC Rezound! - lower left under "Spaces"

    FINALLY!! THANK YOU!!!
    For some reason it is not showing in the phone device list above but look below on lower left under Spaces.  There is now a separate thread for those of us with the HTC Rezound!!

    Thanks for your interest.
    Excuse my ignorance as I'm not sure what you meant by "1 of 5" optimization. Did you mean median of 5 ?
    Regarding swapping pointers, yes it is common sense and rather common among programmers to swap pointers instead of swapping large data types, at the small price of indirect access to the actual data through the pointers.
    However, there is a rather unobvious and quite terrible side effect of using this trick. After the pointer array is sorted, sequential (sorted) access to the actual data throughout the remaining of the program will suffer heavily because of cache misses.
    Memory is being accessed randomly because the pointers still point to the unsorted data causing many many cache misses, which will render the program itself slow, although the sort was fast!!.
    Multi-threaded qsort is a good idea in principle and easy to implement obviously because qsort itself is recursive. The thing is Multi-threaded qsort is actually just stealing CPU time from other cores that might be busy running other apps, this might slow
    down other apps, which might not be ideal for servers. The thing researchers usually try to do is to do the improvement in the algorithm it self.
    I Will try to look at your sorting code, lets see if I can compile it.

  • How can I debug a sequence that has a subsequence is running in a separate thread?

    Hi,
    How can I debug a sequence that has a subsequence is running in a separate thread?
    I have to have a continues check for a  digital in signal to be able to terminate the sequence if a physical button is pushed.
    This is running in a separate thread, but this way I cannot debug the main sequence.
    Is there any workaround for this?
    Thanks,
    Andras

    This KB might help you:
    http://digital.ni.com/public.nsf/websearch/46D1E157756C37E686256CED0075E156?OpenDocument
    Let me know if this does not help.
    Allen P.
    NI

  • Running SSRS report locally in separate thread

    We're using ASP.net with .Net 4, developing with Visual Studio 2012.  We use SSRS 2012sp1 with local reports, so exporting the report ourselves instead of using a reportviewer control (and not using the SQL Reporting service).  The reports are executing
    fine when we export the report in the main thread, but if we spawn a worker thread and run a report there we receive the following error when calling Render():
    Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Failed to load expression host assembly. Details: Invalid token
    for impersonation - it cannot be duplicated.
    We only receive this when running a report that uses expressions on a separate thread.  I've tried running the application pool under all the default built-in accounts (NetworkService, etc), and under admin user accounts to no avail.
    This didn't occur with the previous version of our application which used .net 3.5.  From what I've read, its because of a new security model in .net 4.
    I've tried running the application pool under LocalSystem, that does not help.
    We are not loading any custom DLLs in the report.  I think its trying to load the expression DLL that SSRS compiles from expressions on the report.  We don't have any outside DLLs on the report, only basic report expressions.  This works fine
    in-process, it only fails when we try to run it on a separate thread.
    Microsoft.Reporting.WebForms.LocalProcessingException: An error occurred during local report processing. ---> Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Failed to load expression host assembly. Details: Invalid token for impersonation - it cannot be duplicated.
    at Microsoft.ReportingServices.RdlExpressions.ReportRuntime.ProcessLoadingExprHostException(ObjectType assemblyHolderObjectType, Exception e, ProcessingErrorCode errorCode)
    at Microsoft.ReportingServices.RdlExpressions.ReportRuntime.LoadCompiledCode(IExpressionHostAssemblyHolder expressionHostAssemblyHolder, Boolean includeParameters, Boolean parametersOnly, ObjectModelImpl reportObjectModel, ReportRuntimeSetup runtimeSetup)
    at Microsoft.ReportingServices.OnDemandProcessing.Merge.Init(Boolean includeParameters, Boolean parametersOnly)
    at Microsoft.ReportingServices.OnDemandProcessing.Merge.Init(ParameterInfoCollection parameters)
    at Microsoft.ReportingServices.ReportProcessing.Execution.ProcessReportOdp.CreateReportInstance(OnDemandProcessingContext odpContext, OnDemandMetadata odpMetadata, ReportSnapshot reportSnapshot, Merge& odpMerge)
    at Microsoft.ReportingServices.ReportProcessing.Execution.ProcessReportOdp.Execute(OnDemandProcessingContext& odpContext)
    at Microsoft.ReportingServices.ReportProcessing.Execution.RenderReportOdpInitial.ProcessReport(ProcessingErrorContext errorContext, ExecutionLogContext executionLogContext, UserProfileState& userProfileState)
    at Microsoft.ReportingServices.ReportProcessing.Execution.RenderReport.Execute(IRenderingExtension newRenderer)
    at Microsoft.ReportingServices.ReportProcessing.ReportProcessing.RenderReport(IRenderingExtension newRenderer, DateTime executionTimeStamp, ProcessingContext pc, RenderingContext rc, IChunkFactory yukonCompiledDefinition)
    at Microsoft.Reporting.LocalService.CreateSnapshotAndRender(ReportProcessing repProc, IRenderingExtension renderer, ProcessingContext pc, RenderingContext rc, SubreportCallbackHandler subreportHandler, ParameterInfoCollection parameters, DatasourceCredentialsCollection credentials)
    at Microsoft.Reporting.LocalService.Render(String format, String deviceInfo, String paginationMode, Boolean allowInternalRenderers, IEnumerable dataSources, CreateAndRegisterStream createStreamCallback)
    at Microsoft.Reporting.WebForms.LocalReport.InternalRender(String format, Boolean allowInternalRenderers, String deviceInfo, PageCountMode pageCountMode, CreateAndRegisterStream createStreamCallback, Warning[]& warnings)
    --- End of inner exception stack trace ---
    at Microsoft.Reporting.WebForms.LocalReport.InternalRender(String format, Boolean allowInternalRenderers, String deviceInfo, PageCountMode pageCountMode, CreateAndRegisterStream createStreamCallback, Warning[]& warnings)
    at Microsoft.Reporting.WebForms.LocalReport.InternalRender(String format, Boolean allowInternalRenderers, String deviceInfo, PageCountMode pageCountMode, String& mimeType, String& encoding, String& fileNameExtension, String[]& streams, Warning[]& warnings)
    at Microsoft.Reporting.WebForms.LocalReport.Render(String format, String deviceInfo, PageCountMode pageCountMode, String& mimeType, String& encoding, String& fileNameExtension, String[]& streams, Warning[]& warnings)
    at Microsoft.Reporting.WebForms.Report.Render(String format, String deviceInfo, String& mimeType, String& encoding, String& fileNameExtension, String[]& streams, Warning[]& warnings)
    at IxSS.Infolinx.Report.MicrosoftInfolinxReport.ExportReport(String strFileFullyQualifiedPath, String strExportType, String strFilterDesc, Dictionary`2 extraParams, String area)
    at IxSS.Infolinx.Report.MicrosoftInfolinxReport.ExportReport(String strFileFullyQualifiedPath, String strExportType, String strFilterDesc, Dictionary`2 extraParams)

    Was that a joke?
    If not, no, there is no duplicated token to run the report.  I'm guessing it means some sort of security token, but if its something to do with the user running the application pool, changing that user has no effect.  I've enabled and disabled
    asp.net impersonation to no effect as well.

  • Export from Crystal Reports 2008 viewer fails if run on separate thread

    I have a windows desktop application written in Visual Basic using Visual Studio 2008.  I have installed and am trying Crystal Reports 2008 to run a report.  Everything seems to work well except that when I preview a report (using the viewer control) and click the export button found in the upper left corner of that control, I get the following message:
    Error 5: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made.  Ensure that your Main function has STAThreadAttribute marked on it.  This exception is only raised if a debugger is attached to the process.
    I am a little confused on what to do exactly.  Is the problem because I am running in the Visual Studio 2008 IDE?  It says this exception is only raise if a debugger is attached to the process.  No, I tried running it outside the IDE.  The exception wasn't generated but the application hung when the button was clicked.
    It says the current thread must be set to single thread apartment (STA) mode.  If the report is run on its own thread, is the "current" thread the thread the report is running on or is the main application's UI thread?  I don't think I want to set my main application to single thread apartment mode because it is a multi-threaded application (although I really don't know for sure because I am new to multi-threaded programming). 
    My objective is to allow reports to run asynchronously so that the user can do other things while it is being generated.  Here is the code I use to do this:
        ' Previews the report using a new thread (asynchronously)
        Public Sub PreviewReportAsynch(ByVal sourceDatabase As clsMainApplicationDatabase)
            Dim backgroundProcess As System.ComponentModel.BackgroundWorker
            ' Start a new thread to run this report.
            backgroundProcess = New System.ComponentModel.BackgroundWorker
            Using (backgroundProcess)
                ' Wire the function we want to run to the 'do work' event.
                AddHandler backgroundProcess.DoWork, AddressOf PreviewReportAsynch_Start
                ' Kick off the report asynchronously and return control to the calling process
                backgroundProcess.RunWorkerAsync(sourceDatabase)
            End Using
        End Sub
        Private Sub PreviewReportAsynch_Start(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
            ' The source database needed to call preview report was passed as the only argument
            Call PreviewReport(CType(e.Argument, clsMainApplicationDatabase))
        End Sub
        ' Previews the report.  From the preview window, the user can print it.
        Public Function PreviewReport(ByVal sourceDatabase As clsMainApplicationDatabase) As FunctionEndedResult
            Dim errorBoxTitle As String
            Dim frmPreview As frmReportPreview
            ' Setup error handling
            errorBoxTitle = "Preview " & Name & " Report"
            PreviewReport = FunctionEndedResult.FAILURE
            On Error GoTo PreviewError
            ' Set up the crxReport object
            If InitializeReportProcess(sourceDatabase) <> FunctionEndedResult.SUCCESS Then
                GoTo PreviewExit
            End If
            ' Use the preview form to preview the report
            frmPreview = New frmReportPreview
            frmPreview.Report = crxReport
            frmPreview.ShowDialog()
            ' Save any settings that should persist from one run to the next
            Call SavePersistentSettings()
            ' If we got this far everything is OK.
            PreviewReport = FunctionEndedResult.SUCCESS
    PreviewExit:
            ' Do any cleanup work
            Call CleanupReportProcess(sourceDatabase)
            Exit Function
    PreviewError:
            ' Report error then exit gracefully
            ErrorBox(errorBoxTitle)
            Resume PreviewExit
        End Function
    The variable crxReport is of type ReportDocument and the windows form called 'frmPreview' has only 1 control, the crystal reports viewer. 
    The print button on the viewer works fine.  Just the export button is failing.  Any ideas?

    Hi Trevor.
    Thank you for the reply.  The report document is create on the main UI thread of my application.  The preview form is created and destroyed on the separate thread.  For reasons I won't get into, restructuring the code to move all the initialization stuff inside the preview form is not an option (OK, if you a really curious, I don't always preview a report, sometimes I print and/or export it directly which means the preview form isn't used).
    What I learned through some other research is that there are some things (like COM calls and evidently some OLE automation stuff) that cannot be run on a thread that uses the MTA threading model.   The export button probably uses some of this technology, thus the message stating that an STA threading model is required.  I restructured the code as follows to accomodate this requirement.  Here is a sample:
    ' Previews the report using a new thread (asynchronously)
        Public Sub PreviewReportAsynch(ByVal sourceDatabase As clsMainApplicationDatabase)
            Dim staThread As System.Threading.Thread
            ' Start the preview report function on a new thread
            staThread = New System.Threading.Thread(AddressOf PreviewReportAsynchStep1)
            staThread.SetApartmentState(System.Threading.ApartmentState.MTA)
            staThread.Start(sourceDatabase)
        End Sub
        Private Sub PreviewReportAsynchStep1(ByVal sourceDatabase As Object)
            Dim staThread As System.Threading.Thread
            ' Initialize report preview.  This includes staging any data and configuring the
            ' crystal report document object for use by the crystal report viewer control.
            If InitializeReportProcess(DirectCast(sourceDatabase, clsMainApplicationDatabase)) = FunctionEndedResult.SUCCESS Then
                ' Show the report to the user.  This must be done on an STA thread so we will
                ' start another of that type.  See description of PreviewReportAsynchStep2()
                staThread = New System.Threading.Thread(AddressOf PreviewReportAsynchStep2)
                staThread.SetApartmentState(System.Threading.ApartmentState.STA)
                staThread.Start(mcrxReport)
                ' Wait for step 2 to finish.  This blocks the current thread, but this thread
                ' isn't the main UI thread and this thread has no UI anymore (the progress
                ' form was closed) so it won't matter that is it blocked.
                staThread.Join()
                ' Save any settings that should persist from one successful run to the next
                Call SavePersistentSettings()
            End If
            ' Release the crystal report
            Call CleanupReportProcess(DirectCast(sourceDatabase, clsMainApplicationDatabase))
        End Sub
        ' The preview form must be launched on a thread that use the single-threaded apartment (STA) model.
        ' Threads use the multi-threaded apartment (MTA) model by default.  This is necessary to make the
        ' export and print buttons on the preview form work.  They do not work when running on a
        ' thread using MTA.
        Public Sub PreviewReportAsynchStep2(ByVal crxInitializedReport As Object)
            Dim frmPreview As frmReportPreview
            ' Use the preview form to preview the report.  The preview form contains the crystal reports viewer control.
            frmPreview = New frmReportPreview
            frmPreview.Report = DirectCast(crxInitializedReport, ReportDocument)
            frmPreview.ShowDialog()
        End Sub
    Thanks for your help!
    Andy

  • How do I time out my thread if there is no network traffic

    How do I time out my thread if there is no network traffic for a given time? I have the following code listening for data:
    StringBuffer requestLine = new StringBuffer();
    int c;
    while(true) {
        c = in.read();
        if(c == '\r' || c == '\n') {//Not sure here???
            break;
        requestLine.append((char)c);
    }But how do I time this out if there has been no traffic for lets say 5 minutes?

    Have you redefined 'in'?
    If it's a raw socket connection, you can use the Socket.setSoTimeout method before you open the connection to specify how long it should hold it open if there is no data available.

Maybe you are looking for