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.

Similar Messages

  • How to Generate Synchronized pulses across two separate cards on a PXI system

    Hey,
    I'm trying to generate three pulses from my PXI System for triggering purposes. I have two cards (PXI 6259 and PXI 6115) , each with two counter/timers on them. The 6259 has 32 bit timers, and the 6115 has 24 bit timers.
    Up until now, I only needed two pulses. One was 180us long at 20 Hz, and the other is 5us at 20 Hz, starting 150us after the beginning of the first pulse. I was able to achieve this by generating both pulses on my 6115 card by triggering the shorter pulse off of the rising digital edge of the longer pulse and giving the DAQmx Counter/Timer task an initial delay of 150us.
    The third pulse needs to be identical to the short pulse, only it needs to occur 20us early (130us after the start of the wide pulse). I tried to generate it using the same technique as I used when generating the short pulse, only generating the pulse and reading in the rising digital edge trigger on my 6259 card instead of the 6115. 
    The result was that my pulse trains were asynchronous and the pulse generated on the 6259 card was constantly shifting to the left.
    This puzzled me, so I wrote up a little dummy program to test generating triggered pulses. The results were that when I generated two pulses on the same card, they were always synchronized; however when I generated pulses on separate cards, one of the pulses always shifted.
    I was hoping somebody could suggest a reason that the pulses across cards are asynchronous even though I'm reading in a digital trigger and hopefully a way to rectify the situation and synchronize all of my pulses.  

    The problem, in a nutshell, is that the timebases on the two boards have manufacturing tolerances that will cause them to differ from one another.   The accuracy error is a small fraction of a percent, but the effect on the phasing of your pulses will be cumulative.  That's why you saw the one set of pulses "shifting to the left."
    The solution is to make sure each board derives its pulse timing from a single common timebase.  Fortunately, this is pretty easy to specify with DAQmx, just a little tricky to find.  In the chain of VI's you call to configure the counter pulses, insert a DAQmx Channel property node.   From memory, I *think* you should be looking under something similar to "Counter Output->General->Timebase->Timebase.Src"
    Right click and create a constant or control to define the timebase source.  You should get a dropdown list that includes a wide variety of choices.  Among them are each of the boards' 20 MHz clocks.  By default each task will use a timebase from its own board but this technique lets you route one board's timebase over the PXI backplane with that single property node setting.  DAQmx does most of the dirty work behind the scenes.
    -Kevin P

  • Pushing the limits of continuous high-speed DAQ + processing, with PXI-6115 + PXI-8360

    Hi all,
    I'm trying to do continuous high-speed data acquisition + processing. I currently have:
    Chassis: PXI-1042Q
    AI card: PXI-6115 (x2)
    Link: PXI-8360
    PC CPU: Intel Xeon W3503 (dual-core, 2.40 GHz)
    RAM: 4 GB
    The idea is to continuously grab 8 channels' worth of analog inputs, scan for "events", and if found, log the events to disk.
    My client would like to use the maximum sample rate of 10 MHz, but I found that above 5 MHz, DAQmx Read.vi can no longer keep up (e.g. at 6 MHz, it takes 110 ms to read 100 ms' worth of data).
    Im thinking of getting beefier components, but I'm not sure where the bottleneck is. Here are some thoughts:
    1) The MXI Express link
    The PXI-8360 is rated for a sustained throughput of 100 MB/s.
    I'm not sure how big the data is. PXI-6115's ADC is 12-bit. Does that mean each datum transferred through the MXI cable is 1.5 bytes? Is the data padded? Or is it 8 bytes per datum, because Dbls are being transferred?
    2) The CPU
    In Resource Monitor, I notice that the CPU usage is 0% at 60 kHz, 8% at 61 kHz, and 50% at 70 kHz (meaning that one core is maxed out). I'm surprised that it keeps up all the way until 5 MHz though.
    What causes this high CPU usage? Is it due to the conversion of the data into 1D array of waveforms?
    3) Something else?
    Have I missed something completely? Is what I'm describing even possible?
    Thanks in advance for any advice!

    Hello,
    Each sample will take up 2 bytes, 12 bits data + 4 empty bits. so the PXI-PCI 8360 is only able to transfer a maximum of 50S/s in this case.
    Also, because the PXI bus is shared among all of the cards, two PXI 6115 cards will be trying to transfer 80MS/s or 160MB/s.
    Finally, since the PXI 6115 are DAQ family cards, their specifications aren't really written for continuous data acquisition at the upper end of their sample rate, but I'm interested to know if you can get up to 10MS/s with only one card operating at a time?
    -Jim B
    Applications Engineer, National Instruments
    CLD, CTD

  • PXI-6115 & PXI-6143 on Same Computer, RDA's Future

    Today I installed several PXI-6115 cards and realized that they are only
    supported with traditional DAQ under version 7.2. This is OK for now
    because I'm already limited to traditional DAQ to be able to use RDA.
    However, I was considering adding the new inexpensive S board, the PXI-6143,
    to my system. According to the list of supported boards this board is only
    supported by DAQmx. Questions:
    1. How can these two S boards be used by the same system if programming with
    LabVIEW?
    2. Any guesstimate on if or when the PXI-6115 will be supported by DAQmx?
    3. Any guesstimate on if or when RDA will be supported by DAQmx? RDA
    (remote data acquisition) is an extremely valuable DAQ method and I hope it
    will be supported by D
    AQmx soon!

    Hello,
    You are correct about the support of both boards. The 6143 is only supported in DAQmx, and the 6115 is only supported in Traditional DAQ. Here is the best that I can do for the other questions.
    1. You can program each card in a different driver. This is not a problem at all. The only conflict occurs when you try and program a card in both drivers at the same time. Such as trying to do analog output in Traditional DAQ and analog input in DAQmx.
    2. This is internal information only. For further information I would contact your local sales representative, she/he might be able to assist you further.
    3. Again, if and when is internal information. It is not currently supported. At the moment, you can use remote front panels, or create y
    our own server/client VIs to control a remote DAQ board.
    These are excellent pieces of feedback for our R&D department. I highly encourage anyone who reads this thread to submit product feedback using this link.
    Best regards,
    Justin T.
    National Instruments

  • Does a CQC really need a separate thread/event queue per instance?

    Does a ContinousQueryCache really need a separate thread/event queue per instance?
    Is it possible to get multiple cqc's to share a single event queue?

    Test case to reproduce shown below, i.e. new thread per CQC.
    Sample code:
    =====================================
    NamedCache dummyCache = CacheFactory.getCache("A");
    dummyCache.put("hello", "B");
    dummyCache.put("world", "C");
    ContinuousQueryCache cqcA = new ContinuousQueryCache(dummyCache, new EqualsFilter("toString", "B"), new MultiplexingMapListener() {
    @Override
    protected void onMapEvent(MapEvent mapEvent) {
    System.out.println(Thread.currentThread().getName());
    ContinuousQueryCache cqcB = new ContinuousQueryCache(dummyCache, new EqualsFilter("toString", "C"), new MultiplexingMapListener() {
    @Override
    protected void onMapEvent(MapEvent mapEvent) {
    System.out.println(Thread.currentThread().getName());
    =================================
    Output:
    EventQueue:ContinuousQueryCache{Cache=A, Filter=EqualsFilter(.toString(), B)}
    EventQueue:ContinuousQueryCache{Cache=A, Filter=EqualsFilter(.toString(), C)}
    =================================
    Thread dump:
    Full thread dump Java HotSpot(TM) Client VM (11.2-b01 mixed mode, sharing):
    "EventQueue:ContinuousQueryCache{Cache=A, Filter=EqualsFilter(.toString(), C)}" daemon prio=6 tid=0x034d8800 nid=0x16b4 in Object.wait() [0x03b2f000..0x03b2fa94]
    java.lang.Thread.State: WAITING (on object monitor)
         at java.lang.Object.wait(Native Method)
         - waiting on <0x22d80068> (a com.tangosol.util.TaskDaemon)
         at java.lang.Object.wait(Object.java:485)
         at com.tangosol.util.TaskDaemon.takeNextRipeTask(TaskDaemon.java:345)
         - locked <0x22d80068> (a com.tangosol.util.TaskDaemon)
         at com.tangosol.util.TaskDaemon.run(TaskDaemon.java:103)
         at com.tangosol.util.Daemon$DaemonWorker.run(Daemon.java:714)
         at java.lang.Thread.run(Thread.java:619)
    "EventQueue:ContinuousQueryCache{Cache=A, Filter=EqualsFilter(.toString(), B)}" daemon prio=6 tid=0x034d7400 nid=0x1370 in Object.wait() [0x03adf000..0x03adfb14]
    java.lang.Thread.State: WAITING (on object monitor)
         at java.lang.Object.wait(Native Method)
         - waiting on <0x22d80138> (a com.tangosol.util.TaskDaemon)
         at java.lang.Object.wait(Object.java:485)
         at com.tangosol.util.TaskDaemon.takeNextRipeTask(TaskDaemon.java:345)
         - locked <0x22d80138> (a com.tangosol.util.TaskDaemon)
         at com.tangosol.util.TaskDaemon.run(TaskDaemon.java:103)
         at com.tangosol.util.Daemon$DaemonWorker.run(Daemon.java:714)
         at java.lang.Thread.run(Thread.java:619)

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

  • 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

  • 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

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

  • Does URLLoader load data in a separate thread?

    I understand the Flash and AS3 is single-threaded, at least at the user level.
    However, I would like to understand how asynchronous data loading is handled by the Flash player.
    For instance, if I run CPU-intensive code that runs beyond the normal frame (lets say it runs on ENTER_FRAME, and consumes 1/4 per call).  Does this leave any CPU cycles to load data from a URLLoader?
    If http loading is truly synchronous, right down to handling the TCP/IP stack, one would get horrible performance.
    In Windows programming, I can do http access asynchronously (in which case the Windows libraries are doing either input on a separate thread, or doing hardware-level interrupts to handle the data -- I provide an asynchronous callback that may be on its own thread).  Or, I can do synchronous download, in which case there will be hardware buffering, but my application is actively waiting for each buffer of data to be delivered by the hardware/OS combination.
    URLLoader is asynchronous, but what does that mean?  Does it mean that I can run the CPU and still download data?  Or, will my download speed slow to a crawl if my Flash application is under heavy CPU load?
    Understanding how this works will help me design my product better, which both uses a lot of CPU, and downloads a lot of data (to the bandwidth limit of the network, if possible).

    >>"no data handling can occur if the cpu is 100% occupied.  so, the download will slow/stop."
    Operating systems have pre-emptive multitasking, so if download were in another thread, it could still operate.
    My CPU has 4 cores.  So by 100% busy, I meant that I am getting close to maxing out the main thread of Flash, which only uses one core.
    >>data downloading being asynchronous means while data is downloading the cpu and your actionscript can do other things
    This is my question exactly.  Asynchronous can mean many things.  At the lowest layer, at least one "buffer" of data (who knows what size) has to be downloaded in a separate thread, or by hardware, or by the browser, etc.  Flash could have a background thread internally that grabs data from this buffer, and does something with it.  Or, Flash could rely on polling this buffer on the main thread in-between frames.  The last method would be bad, as it would rely on the user not using the complete CPU usage per frame.
    The real truth may be a combination of these two -- it may download in a background thread, but only up to some limit, at which point the Flash main thread has do internally grab it?
    >>but it is possible to have other actionscript tasks or flash animations interfere with downloading.
    My question is, how much care and feeding does the download require?  Does it work quite well by itself, and is rarely affected by AS3 CPU use, or is there a requirement to not use up all of the CPU per-frame in order for the download to proceed?  In my case, I may stretch my frames out to 1/4 second, as I do intensive CPU work.  Would this slow or stop my downloads?
    Thanks for the helpful reply -- I would love a bit more detail though.
    Also, I'm more likely to be using URLStream in my actual implementation.

  • 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

  • Very slow JTextArea updates even as separate thread

    Hi,
    I am trying to report output of a dynamic stream as a JFrame that contains JTextArea. The module is part of my big SWING application. The problem is JTextArea only shows update after the stream is empty. I have tried the following things
    * Stream pocessed as separate thread.
    * Thread priority set to maximum.
    * function updateUI is called after a batch of lines have been written.
    Here's the code to activate the thread
    StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT",outputWindow);
    outputGobbler.start();Here's the code for StreamGobbler class with JTextArea and JFrame
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        String thsContent;
        JTextArea outputWindow;
        StreamGobbler(InputStream is, String type,JTextArea dPane){
            this.is = is;
            this.type = type;
         outputWindow=dPane;
         thsContent=new String("");
        public void run(){
         int myMode=1;
         int lineCt=0;
         String myLineSep=new String(System.getProperty("line.separator"));
            try{
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null){
              if(myMode==1){
                  setDisplayWindow();
                  myMode=2;
                 System.out.println(type + ">" + line);
              outputWindow.append(line+myLineSep);
              lineCt++;
              if(lineCt==10){
                  outputWindow.updateUI();
                  lineCt=0;
             if(myMode==2)
              outputWindow.updateUI();
         } catch (IOException ioe){
             ioe.printStackTrace(); 
        public void setDisplayWindow(){
         setPriority(MAX_PRIORITY);
         outputWindow=new JTextArea("output",80,300);
         JScrollPane scrollingArea1= new JScrollPane(outputWindow);
         scrollingArea1.setPreferredSize(new Dimension(440, 210));
         scrollingArea1.setMinimumSize(new Dimension(400, 200));
         scrollingArea1.setMaximumSize(new Dimension(1000, 500));
         outputWindow.setEditable(false);
         JFrame displayWindow=new JFrame("Display Window");
         displayWindow.setContentPane(scrollingArea1);
         displayWindow.pack();
         displayWindow.setVisible(true);
    }

    Thanks for your reply sir.
    JDialog won't work for me. I need a JComponent that lets incremental display of content (like append method used in JTextArea).
    Below is my example code that you can run and see what I am trying to do. In this example the lines generated by ping are very few. My application actually uses an exe file instead of ping command. The .exe generates few KB of output. I am trying to stream the output of this exe to JTextArea. I am sorry I am not able to provied the actual exe itself.
    The example given below works well as the JTextArea gets filled as the output is printed on the command prompt window. It is because of limited resource consumption by ping command. This does not happen with my .exe file. The JTextArea is filled only after the .exe file stops executing. The few hundred lines printed by the .exe file appears suddenly instead of a continuous manner (Although the System.out.println continued to print the output on the command prompt console continuously like the ping example below). Thus there is a delay between the console output and JTextArea when using my exe file.
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        String thsContent;
        JTextArea outputWindow;
        StreamGobbler(InputStream is, String type){
            this.is = is;
            this.type = type;
         thsContent=new String("");
        public void run(){
         int myMode=1;
         int lineCt=0;
         String myLineSep=new String(System.getProperty("line.separator"));
            try{
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null){
              if(myMode==1){
                  setDisplayWindow();
                  myMode=2;
                 System.out.println(type + ">" + line);
              ///          thsContent=thsContent.concat(line);
              outputWindow.append(line+myLineSep);
              ///          outputWindow.append();
              lineCt++;
              if(lineCt==1){
                  outputWindow.updateUI();
                  lineCt=0;
             if(myMode==2)
              outputWindow.updateUI();
         } catch (IOException ioe){
             ioe.printStackTrace(); 
        public void setDisplayWindow(){
         setPriority(MAX_PRIORITY);
         outputWindow=new JTextArea("output",80,300);
         JScrollPane scrollingArea1= new JScrollPane(outputWindow);
         scrollingArea1.setPreferredSize(new Dimension(440, 210));
         scrollingArea1.setMinimumSize(new Dimension(400, 200));
         scrollingArea1.setMaximumSize(new Dimension(1000, 500));
         outputWindow.setEditable(false);
         ///     JPanel myPanel=new JPanel();
         ///     myPanel.add(scrollingArea1);
         JFrame displayWindow=new JFrame("MASPIC Run Window");
         ///     displayWindow.setContentPane(myPanel);
         displayWindow.setContentPane(scrollingArea1);
         displayWindow.pack();
         displayWindow.setVisible(true);
        public static void main(String args[]) {
    try{           
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("ping localhost");
                // any error message?
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");           
                // any output?
             ///            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT",outputWindow);
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
                // kick them off
             ///            errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            } catch (Throwable t){
                t.printStackTrace();
    }

  • How to make a function in separate thread

    i need to make a function that is running in a separate thread
    Thank's in advance

    Thank's
    but in my program i have a main class which is a server it runs forever.
    from the main class when i call a function it runs in a separate thread and returns the result to the callee and the main function continue it's work
    class server
    //this function when called must be in separate thread
    public int function(int x)
    //there could be wait here or sleep
    return x*2;
    public static void main(String[] args)
    // Run RMI server
    i hope u understand me!!!
    Thank's

  • Separate thread for input stream and output stream.

    Hi Techies,
    In a socket connection, can we run the input stream and output stream in separate threads. actually in my case, the input stream will be getting the input regularly and output stream will send data very rare. so if i impelment them in one class then unless there is data to send output stream will be blocked. i was thinking to impelment both the streams in separate threads. is it a good way? so how to implement it. your guidance will be of great help.
    thanks in advance.

    JavaBreather wrote:
    Hi Techies,
    In a socket connection, can we run the input stream and output stream in separate threads.I would say this is the most common way of handling sockets and threads. esp pre-NIO.
    Iis it a good way? so how to implement it. your guidance will be of great help.Once you have a socket, create two threads, one which does the reading and one which does the writing.
    You could use BlockingQueues to abstract access to these threads. i.e. the reading thread reads something from the socket and adds it to the BlockingQueue. The writing thread take()s something froma second BlockingQueue and writes it to the Socket. This way you add things to write or get thing to process by looking at the BlockingQueues.

Maybe you are looking for

  • Problem in Netweaver ABAP full trial version

    Dear Freinds i have installed SAP Netweaver ABAP Full Trial version.  But There is problem when i create any program SE38. That program is created and activated but could not be executed. When i press F8 no response comes. can any body give the solut

  • Thumbnails do not show - and each time I start, it creates 12900 thumbnails...

    I have Adobe Elements 12. If I look at all my pics, the newer ones - mostly if I zoom out a lot, meaning that the thumbnails are very small - then the sandclock Comes and stays... if I zoom in, then if the thumbnails become quite a large size, then t

  • Where to put 1945 constants?

    Iin the UTF-8 charset, between (19968 < character < 40846) are 1945 characters that i am interested in. They are now in a text file. My only purpose is to test if a character is inside this Set. my design: (1) use an unmodifiable Set<Integer>. (2) ma

  • DLLs - Export of VI mandatory

    I'm reading the Help entitled "Building a Shared Library (DLL)", and step 5 says, "...select the VI you want to define as an exported VI in a shared library.  You must define at least one VI to export as a function in the shared library". What does t

  • Don't understand getValueBinding()

    Hi All, Can someone please help me with the following. I have a set of HtmlInputText, for each htmlInputText box that I create I do the following (I am displaying this within the panelGrid where every row has a set of these HtmlInputText): HtmlInputT