VI calling from a multi-thread Teststand

Hello,
My test system tests four UUTs at the same time(with batch mode in TS), the code is based on LabVIEW and call from TS, so every step the same VI will be accessed by four thread. however, it runs quite slow even i set the reentrant execution in VI propertise.
My Quesition:
Can I do it like this in multi-thread mode of TS?
How can I make it fast? (convert VI to dll?????)
Any help will be appreciated.
Thanks,Steven

Hello Allen,
Thanks for your help.
Problem: I have a LabVIEW VI with parallel code blocks. These blocks run in parallel as expected when I run my VI directly or from a top level VI. However, the code blocks seem to run sequentially when I call my VI from TestStand. Why is this happening and how can I fix it?
Solution: In order to fix this behavior, simply set the VI Properties of "Execution" of your LabVIEW VI to "Other 1" or "Other 2". This change will make the parallel code blocks in your LabVIEW VI run in parallel as expected. To change this setting, from your LabVIEW VI, go to File»VI Properties. Select the Execution category. Change the Preferred Execution System to be either other 1 or other 2.
You need to make this change to any LabVIEW VI with parallel code blocks that is called from TestStand. The reason for this is that TestStand is using the LabVIEW ActiveX interface to run LabVIEW VIs. The LabVIEW ActiveX interface sets the caller's execution system to "User Interface" by default. This execution system is not recommended for a VI with parallel code blocks. If your LabVIEW VI's execution system is set to "Same as caller" (which is the default setting when creating a new LabVIEW VI), then it is executed in the User Interface thread when run through the LabVIEW ActiveX interface. This prevents the blocks to be executed in parallel.
In fact, only one block in my LabVIEW code, but it accessed by four thread from TS. I am sure that my VI can be accessed by four thread simultaneously if I enable the reentrant excution in VI property. I also have tried what mentioned in above document but no use.
However, if i only add a 1000ms delay to my LabView code instead of the 'calculation', it is fast enough!  what is happening or something i set wrong?
I don't want to convert all my LabView code to DLL cos too many VIs here, and difficult for mantenance either.
Any other good solution???
Thank you Allen...
Steven

Similar Messages

  • System() from a multi-threaded app

    The man page for system(3S) states that its MT-Level is "unsafe." Nonetheless we need to call system() from a multi-threaded application. At present we "just go ahead and do it," and of course it doesn't work well. I'm not entirely sure of the details of the failure -- it's more a colleague's baby than mine -- but I believe the system() call often fails to complete ("hangs").
    Is there a thread-safe equivalent-or-replacement for system()? Surely the need to launch other applications from a multi-threaded application is commonplace today? How is it done safely-and-correctly?

    Hi,
    system() is not thread safe because it internally uses vfork() system call which in turn is not MT-safe . When you do a vfork()/fork1() in threaded applications only the thread which issues the call gets duplicated in the child process , which could result in dead lock problems . Solution of running system() under the protection of a lock may not help to avoid this problem.
    If you're using Solaris thread library , fork() + exec() is a safe substitute for system() . If you are using Posix library , use pthread_atfork() to make sure that you handle the locks properly before/after forking.
    Hope this helps.
    Thanks,
    Prajeesh

  • Connection Pooling in OCCI Vs Multi-Threading.

    Hi,
    I am working on an application in which I am using OCCI( Oracle C++ Call Interface)  and multi-threading concepts.
    My application is having different clients( Ex: Client-A, Client-B) and I am offering a set of operations( functions that trigger the Stored Procedures of DataBase ) which are common to all the clients.Each Client can send asynchronous requests of any number.So, is there any chance of using single connection( not connection pooling) to the Data Base for all the clients to manage their requests ?
    Note: Multi-threaded requests are also allowed from each client.
    How can I co-relate multithreading and Connection Pooling in OCCI?
    Can I you multi-threading without Connection Pooling? If so how?
    Will the connection pooling is needed if there is no multi threading concept in my application?
    Please help me on this. Very urgent.
    Thanks in Advance..:)

    Connections are resources that the application uses and a fewer connections can be used by multiple threads if the threads are not always busy with the database activity only, and are doing other work too. This sharing (pooling) can be implemented by the application or the application can leverage the connection pooling features offered by OCI/OCCI (recommended).
    Be aware of connections vs sessions and sharing them (refer to :
    OCI Programming Advanced Topics
    OCCIConnectionPool is to pool connections and OCCIStatelessConnectionPool is to pool sessions. Please see the differences in the above link and apply as appropriate.

  • What is multi threading?

    Hi all,
    What is multi threading? How to implement multi threading in ABAP?
    Regards,
    Bryan

    Hi
    How the vision connector framework works
    The connector interacts with an SAP application using connector modules. The connector modules make calls to SAP's Native Interfaces and pass data (business object or event data) to and from an SAP application. The connector's flexible design enables different modules to be used for different tasks such as initializing the connector with the SAP application or passing business object data.
    Communication between the connector and an SAP application
    The connector uses SAP's Remote Function Call (RFC) library to communicate with an SAP application. SAP's RFC API allows external programs to call ABAP function modules within an SAP application.
    Processing business objects
    The connector is metadata driven. Metadata, in the WebSphere business integration system, is application-specific data that is stored in business objects and that assists a connector module in its interaction with the application. A metadata-driven connector module handles each business object that it supports based on metadata encoded in the business object definition rather than on instructions hard-coded in the connector module.
    Business object metadata includes the structure of a business object, the settings of its attribute properties, and the content of its application-specific information. Because connector modules are metadata driven, they can handle new or modified business objects without requiring modifications to the connector-module code.
    The vision connector framework uses the value of the verb application-specific information in the top-level business object to call the appropriate connector module to process the business object. The verb application-specific information provides the classname of the connector module.
    The verb application-specific information of most top-level business objects must identify the classname of the connector module. The syntax of this verb application-specific information is:
    AppSpecificInfo = PartialPackageName.ClassName,
    For example,
    AppSpecificInfo = sap.sapextensionmodule.VSapBOHandler,
    In this example, sap.sapextensionmodule is the partial package name, and VSapBOHandler is the classname. The full package name includes the com.crossworlds.connectors prefix, which the WebSphere business integration system adds to the name automatically. In other words, the full text of the example is:
    com.crossworlds.connectors.sap.sapextensionmodule.VSapBOHandler
    Note:
    The verb application-specific information of most top-level business objects must use a comma (,) delimiter after the connector classname. However, the Server verb, which is used by the RFC Server Module, is delimited instead by a semi-colon (;). For information about the Server verb, see How the RFC Server Module works and Supported verbs.
    You need not specify the package name and classname for the verb application-specific information if the business object is used:
    by the ALE Module to process application events; however, when you use the ALE Module to process service call requests, you must specify the package name and classname
    by the ABAP Extension Module, which uses the default business object handler (sap.sapextensionmodule.VSapBOHandler)
    Important:
    Customer-generated connector modules that process business objects for the RFC Server Module must specify a full package name, which must begin with bapi. For example, bapi.client.Bapi_customer_getdetail2. The full package name in this example is bapi.client, and the classname is Bapi_customer_getdetail2.
    Most business object processing is specific to each connector module. By default the connector uses the ABAP Extension Module. For more information on business object processing for the ABAP Extension Module, see Installing and customizing the ABAP Extension Module and Business object data routing to ABAP handlers. .
    For more information on specifying verb application-specific information for the ALE Module, see Event processing and Processing multiple IDocs with a wrapper business object.
    Processing multiple concurrent interactions
    The Adapter Framework can create separate threads for processing an application event and a business object request. When processing multiple requests from the integration broker, it can create multiple threads to handle multiple business object requests. For example, when InterChange Server is the integration broker, the connector can receive multiple business object requests from multiple collaborations or from a multi-threaded collaboration.
    Figure 4 illustrates the multi-threading architecture.
    Figure 4. Multi-Threading Architecture of the Connector for SAP
    Event processing
    The connector performs the following steps when handling a poll call:
    The Adapter Framework creates a single dedicated thread to handle poll calls. This thread calls the pollForEvents() method of the vision connector framework at the frequency specified in the PollFrequency configuration property.
    The thread polls SAP, which uses a dialog process to locate and return the event.
    Note:
    If the connector's MaxNumberOfConnections configuration property evaluates to a number greater than 1, the vision connector framework dedicates a connection to SAP for polling. If MaxNumberOfConnections evaluates to 1, event and service-call request processing share a single connection to SAP.
    The polling thread dies only when the connector shuts down.
    Note:
    Because the RFC Server connector agent pushes events out of SAP instead of polling for events, it spawns its own threads instead of using threads created by the connector framework. Because the ALE connector agent uses the RFC Server connector agent to access events, it also spawns its own threads instead of using threads created by the connector framework when it processes events.
    Request processing
    Independently of polling, the Adapter Framework can create multiple request-processing threads, one for each request business object. Each request thread instantiates the appropriate business object handler.
    For example, when processing business object requests from InterChange Server, the number and type of business object handlers depends on the number and type of the collaborations sending the requests:
    If multiple collaborations send business objects, each request thread instantiates a business object handler of the appropriate type.
    If a multi-threaded collaboration sends multiple business objects of the same type, the request threads instantiate an equal number of business object handlers of that type.
    If the connector's MaxNumberOfConnections configuration property evaluates to a number greater than 1, the vision connector framework dedicates one connection to SAP for polling and allocates the remaining connections to a pool used only for request processing.
    As illustrated in Figure 4, the connector performs the following steps when handling a business object request:
    The Adapter Framework creates a separate thread for each business object request. Each thread calls the doVerbFor() method of the Vision business object handler.
    If the connector's MaxNumberOfConnections configuration property evaluates to a number greater than 1, the Vision business object handler checks the vision connector framework's connection pool to determine if a connection handle is available.
    If the handle is available, the thread sends the request to SAP, which uses a dialog process to handle the request.
    If the handle is not available, the thread waits until one becomes available. Thread sequencing determines the order in which each business object handler thread claims or waits for an available connection handle.
    If the connector's MaxNumberOfConnections configuration property evaluates to 1, the Vision business object handler shares a connection with event processing.
    SAP releases the dialog process after it completes processing and sends a return code.
    The connector releases the connection handle after it receives the return code from SAP.
    Setting the number of available connections
    Use the MaxNumberOfConnections configuration property to specify the maximum number of connection handles available. The number of connections cannot exceed the number of dialog processes.
    SAP locks the dialog process while processing an interaction, releasing it only when the interaction completes. Therefore, multiple concurrent requests lock an equal number of dialog processes until processing finishes.
    Important:
    Before setting a value for MaxNumberOfConnections, contact your SAP BASIS administrator to determine an appropriate value to maximize throughput without negatively affecting performance on the application server.
    Support for multiple connections
    By default the connector supports multiple-threads.
    <b>
    REWARD IF USEFULL</b>

  • TPEPERM on multi thread clients

    Good day experts!
    We have a problem with our client experiencing TPEPERM when they multi thread on their side. Both our passwords are the same
    Could this be a version issue
    Our version of tuxedo is 6.5
    Greatly appreciate your help

    Multithreading is supported in Tuxedo only for release 7.1 and later. (I recall that we did implement a limited version of client thread support in Tuxedo 6.5 for some platforms that required setting an environment variable and may have required getting special binaries from BEA, but this is no longer supported.)
    However, if you make Tuxedo calls from only one thread in your program and have other threads that do not access Tuxedo, then it is OK to use multiple threads in Tuxedo 6.5.
    You will need to upgrade to a later version of Tuxedo if you want to access Tuxedo from more than one thread within a process.
    Ed

  • Multi-threading

    Hi folks,
    I need to have one Connection object and multiple Statement objects created from this Connection Object. Is it safe to do this from a multi-threaded application?
    Does createStatement() destroy any previously created Statement?

    You can have multiple statements in different threads coming of the same connection.
    But, all such statements will be part of the same transacion. A DML in one thread will be reflected in a query in another thread.
    If this not what you wanted, then you can have a connection pool and get connections from it in the individual threads.

  • Environment.Exit hangs when called from an application domain exception handler

    I've implemented a handler for exceptions not thrown in the main GUI thread of my C# WinForms application, as follows:
        AppDomain.CurrentDomain.UnhandledException  += OnUnhandledExceptionThrown;
    This handler is called from a background thread. The last statement in this handler is a call to
    Environment.Exit with the application exit code. However, the application hangs in this call. From within Visual Studio, it hangs and I'm unable to break the application; I have to use Task Manager to terminate Visual Studio. Environment.Exit
    works fine when called from the unhandled exception handler for the GUI thread. Is there a better way to terminate the application in the context of an unhandled exception thrown by a background thread?

    Are you just trying to avoid a crash? Environment.Exit can cause deadlocking if exiting in the wrong kind of scenario; if you're just trying to avoid a crash, use
    GetCurrentProcess with
    TerminateProcess to terminate your own process.  It skips the notification phases that Environment.Exit uses which prevents the common deadlock scenarios.
    WinSDK Support Team Blog: http://blogs.msdn.com/b/winsdk/

  • Show truly dangerous to call from main?

    In this JDC tutorial
    http://java.sun.com/developer/JDCTechTips/2003/tt1208.html#1
    the author claims that it is dangerous to call a Frame's show method from the thread executing your program's main, which is probably how 99% of us do it. Instead he claims that to be truly multithread safe, you need to call show from the AWT event thread using the invokeLater mechanism.
    Is this really true? Does anyone know of a good discussion of this elsewhere? And if so, then how come Sun does not document it, say, in the show method? It is a disgrace to not mention such a critical fact right in the method itself if it is truly necessary.
    I presume that if the author's point is true, then it holds for any Window or subclass (e.g. Dialog as well as Frame)?
    Finally: if you truly do need to call show on the AWT event thread, then what about calling pack? (Contrary to what his article seems to say, calling show does NOT seem to automaticly call pack, at least for Frames.) Should you also only call pack from the event thread too? And are there any other methods that should only be called from the event thread?

    I would question the true risk here. What the author of the article is describing is creating more frames or dialogs from the main thread. However the creation of the initial frame is pretty safe to call show on from your primary thread.
    In general it is always a good practice to do all GUI related work in the event thread. Updating fields/labels, etc. should be done in the event thread and therefore calling show on a sub frame or dialog should also be done in the event thread.

  • HELP!....GUI crashes when i call a multi-threaded program from it

    Hi..I have encountered a problem in my end of year project, which i cant see to solve. The problem is i am starting a multi-threaded program for a JButton on a GUI. All though this starts the other program it crashes the GUI completely how do i stop this.
    this is the code i use to call the threaded program.
    public void actionPerformed(ActionEvent e)
    Object target=e.getSource();
    String line = new String();
    if( target==b1 )
         try
    cl = new client();
         cl.startup();
         catch(Exception ex){ex.printStackTrace();}
    thanks Mike

    No there is no exceptions being given. this is one of the reasons why i dont no what to do. i thought myself that the threaded was taking all the resources and not going back to the GUI. if this is the case is there anyway that i can call back the GUI and keep the threaded program running?
    thanks
    mike.

  • SSRS - Is there a multi thread safe way of displaying information from a DataSet in a Report Header?

     In order to dynamically display data in the Report Header based in the current record of the Dataset, we started using Shared Variables, we initially used ReportItems!SomeTextbox.Value, but we noticed that when SomeTextbox was not rendered in the body
    (usually because a comment section grow to occupy most of the page if not more than one page), then the ReportItem printed a blank/null value.
    So, a method was defined in the Code section of the report that would set the value to the shared variable:
    public shared Params as String
    public shared Function SetValues(Param as String ) as String
    Params = Param
    Return Params 
    End Function
    Which would be called in the detail section of the tablix, then in the header a textbox would hold the following expression:
    =Code.Params
    This worked beautifully since, it now didn't mattered that the body section didn't had the SetValues call, the variable persited and the Header displayed the correct value. Our problem now is that when the report is being called in different threads with
    different data, the variable being shared/static gets modified by all the reports being run at the same time. 
    So far I've tried several things:
    - The variables need to be shared, otherwise the value set in the Body can't be seen by the header.
    - Using Hashtables behaves exactly like the ReportItem option.
    - Using a C# DLL with non static variables to take care of this, didn't work because apparently when the DLL is being called by the Body generates a different instance of the DLL than when it's called from the header.
    So is there a way to deal with this issue in a multi thread safe way?
    Thanks in advance!
     

    Hi Angel,
    Per my understanding that you want to dynamic display the group data in the report header, you have set page break based on the group, so when click to the next page, the report hearder will change according to the value in the group, when you are using
    the shared variables you got the multiple thread safe problem, right?
    I have tested on my local environment and can reproduce the issue, according to the multiple safe problem the better way is to use the harshtable behaves in the custom code,  you have mentioned that you have tryied touse the harshtable but finally got
    the same result as using the ReportItem!TextBox.Value, the problem can be cuased by the logic of the code that not works fine.
    Please reference to the custom code below which works fine and can get all the expect value display on every page:
    Shared ht As System.Collections.Hashtable = New System.Collections.Hashtable
    Public Function SetGroupHeader( ByVal group As Object _
    ,ByRef groupName As String _
    ,ByRef userID As String) As String
    Dim key As String = groupName & userID
    If Not group Is Nothing Then
    Dim g As String = CType(group, String)
    If Not (ht.ContainsKey(key)) Then
    ' must be the first pass so set the current group to group
    ht.Add(key, g)
    Else
    If Not (ht(key).Equals(g)) Then
    ht(key) = g
    End If
    End If
    End If
    Return ht(key)
    End Function
    Using this exprssion in the textbox of the reportheader:
    =Code.SetGroupHeader(ReportItems!Language.Value,"GroupName", User!UserID)
    Links belowe about the hashtable and the mutiple threads safe problem for your reference:
    http://stackoverflow.com/questions/2067537/ssrs-code-shared-variables-and-simultaneous-report-execution
    http://sqlserverbiblog.wordpress.com/2011/10/10/using-custom-code-functions-in-reporting-services-reports/
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • Cannot get bitmap from native DLL from multi threaded Java app.

    I have a native DLL that gives me a HBITMAP (Windows handle to bitmap). I have made a JNI wrapper for this that gives me a BufferedImage back. The native code simple gets the actual bitmap for the handle, converts the RGB byte triplets to RGB ints, puts this in a jintArray and creates a BufferedImage.
    This all works fine within a single Java thread. If I do this multi threaded (thread 1 calls the native function and several seconds later, thread 2 calls the native function) I keep getting the last image of the first thread. Can enyone help me out?
    I know that this is probably a question for MSDN but I just know that they will tell me its a JNI question.
    The native code:
    JNIEXPORT jobject JNICALL Java_somenamespace_getPicture
    (JNIEnv *env, jclass cl, jstring serialNumber)
    jobject jImage;
    jclass jImageClass;
    jmethodID jMethod;
    jfieldID jField;
    jintArray rgbArray;
    char *str;
    char *charArray;
    int *intArray;
    int w, h, index, type;
    HBITMAP hbmp;
    BITMAP bmp;
    str = (char*)((*env)->GetStringUTFChars(env, serialNumber, NULL));
    // Gets the HBITMAP handle from the native DLL. The first argument is to select the device, based on serial number.
    getPicture(str, &hbmp);
    (*env)->ReleaseStringUTFChars(env, serialNumber, str);
    // Get the BITMAP for the HBITMAP
    GetObject(hbmp, sizeof(BITMAP), &bmp);
    // Create my BufferedImage
    jImageClass = (*env)->FindClass(env, "java/awt/image/BufferedImage");
    jMethod = (*env)->GetMethodID(env, jImageClass, "<init>", "(III)V");
    jField = (*env)->GetStaticFieldID(env, jImageClass, "TYPE_INT_RGB", "I");
    type = (*env)->GetStaticIntField(env, jImageClass, jField);
    jImage = (*env)->NewObject(env, jImageClass, jMethod, bmp.bmWidth, bmp.bmHeight, type);
    // Get the RGB byte triplets of the BITMAP
    charArray = (char *)malloc(sizeof(char) * bmp.bmHeight * bmp.bmWidth * 3);
    GetBitmapBits(hbmp, sizeof(char) * bmp.bmHeight * bmp.bmWidth * 3, charArray);
    // Allocate space to store the RGB ints and convert the RGB byte triplets to RGB ints
    intArray = (int *)malloc(sizeof(int) * bmp.bmHeight * bmp.bmWidth);
    index = 0;
    for (h = 0; h < bmp.bmHeight; ++h)
    for (w = 0; w < bmp.bmWidth; ++w)
    int b = *(charArray + index * 3) & 0xFF;
    int g = *(charArray + index * 3 + 1) & 0xFF;
    int r = *(charArray + index * 3 + 2) & 0xFF;
    *(intArray + index) = 0xFF000000 | (r << 16) | (g << 8) | b;
    ++index;
    // Create a jintArray for the C RGB ints
    rgbArray = (*env)->NewIntArray(env, bmp.bmHeight * bmp.bmWidth);
    (*env)->SetIntArrayRegion(env, rgbArray, 0, bmp.bmHeight * bmp.bmWidth, (jint*)intArray);
    // Use BufferedImage.setRGB() to fill the image
    jMethod = (*env)->GetMethodID(env, jImageClass, "setRGB", "(IIII[III)V");
    (*env)->CallVoidMethod(env, jImage, jMethod,
    0, // int startX
    0, // int startY
    bmp.bmWidth, // int width
    bmp.bmHeight, // int height
    rgbArray, // int[] rgbArray
    0, // int offset
    bmp.bmWidth); // int scansize
    // Free stuff
    (*env)->DeleteLocalRef(env, rgbArray);
    free(charArray);
    free(intArray);
    return jImage;
    }I already tried working with native HDCs (GetDC, CreateCompatibleBitmap, SelectObject, GetDIBits, ...) but this just complicates stuff and gives me the same result.

    Have you verified what the "native DLL" gives you back on the second call?The HBITMAP handle returned is the same each call (no matter which thread). The actual BITMAP associated with this handle is only updated in the first thread.
    How are you determining that the image is the same?If I point the camera (I don't get a stream, I just get individual images) to a moving scene, I get different images for each call from within the first thread. The second thread only gets the latest image from the first thread. There is no concurrency of the threads and all methods are synchronized.
    Specifically did you verify that the problem is not that your test code itself is using the same instance?Yes, I tested the native side as well as the Java side. The BufferedImage is always an exact copy of the native BITMAP.
    Try printing out the hash for each instance.I have written the image to a file in the native code itself to eliminate anything related to the mechanism of returning the BufferedImage. This had the same result.
    The return values of all native calls all indicate successful calls.
    I am suspecting the native side of creating a second graphical context for the second thread while it keeps refering to the first context.
    (I will start a thread on the MSDN as well and will post here if anything turns up.)

  • How to call a report with a bind variable from a multi-record block

    Hi,
    I have created a report using the BI Publisher functionality. I did all the integration, created the SQL Query and uploaded the template. Up till here everythings fine!
    My SQL Query has 2 bind variables.
    I will call my report from a multi record block, at the end of each record an icon is shown which the user can click to open the report.
    I created a column link for this item (PRINT_REPORT=Inschrijvingsformulier) but I do not manage to pass the parameters to my report. The parameters I want to pass are 2 columns in this Multi Record block.
    I created 2 hidden fields on the page P9_PARAMETER1, P9_PARAMETER2 with the same names as my bind variables and fill this in with the values #PARAMETER1#, #PARAMETER2# from the multi record block.
    It seems it does not work as my report stays empty. (also XML file stays empty).
    Am I trying the wrong way?
    Thanks for any advice,
    Kris

    hi khadeer,
         create one report program and write the required code,and call this function module 'SSF_FUNCTION_MODULE_NAME' and give your smartform name  and also when u activate ur smart form u will get one function module call that function module also and specify any tables used...
    i think this solves ur problem...
    any queries revert back..
    pls reward points if helpful,
    shylaja

  • Calling a delegate on the UI thread from a work thread inside a child class.

    Hi All,
    I've run into a snag developing a WPF multithreaded app where I need to call a method on the UI thread from my work thread, where the work thread is running a different class.
    Currently I am trying to use a delegate and an event in the 2nd class to call a method in the 1st class on the UI thread. This so far is not working as because the 2nd class is running in its own thread, it causes a runtime error when attempting to call
    the event.
    I've seen lots of solutions referring to using the dispatcher to solve this by invoking the code, however my work thread is running a different class than my UI thread, so it seems the dispatcher is not available?
    Below is as simplified an example as I can make of what I am trying to achieve. Currently the below code results in a "The calling thread cannot access this object because a different thread owns it." exception at runtime.
    The XAML side of this just produces a button connected to startThread2_Click() and a label which is then intended to be updated by the 2nd thread calling the updateLabelThreaded() function in the first thread when the button is clicked.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Windows.Threading;
    using System.Threading;
    namespace multithreadtest
    public delegate void runInParent();
    public partial class MainWindow : Window
    public MainWindow()
    InitializeComponent();
    threadUpdateLabel.Content = "Thread 1";
    private void startThread2_Click(object sender, RoutedEventArgs e)
    thread2Class _Thread2 = new thread2Class();
    _Thread2.runInParentEvent += new runInParent(updateLabelThreaded);
    Thread thread = new Thread(new ThreadStart(_Thread2.threadedTestFunction));
    thread.Start();
    public void updateLabelThreaded()
    threadUpdateLabel.Content = "Thread 2 called me!";
    public class thread2Class
    public event runInParent runInParentEvent;
    public void threadedTestFunction()
    if (runInParentEvent != null)
    runInParentEvent();
    I'm unfortunately not very experienced with c# so I may well be going the complete wrong way about what I'm trying to do. In the larger application I am writing, fundamentally I just need to be able to call a codeblock in the UI thread when I'm in a different
    class on another thread (I am updating many different items on the UI thread when the work thread has performed certain steps, so ideally I want to keep as much UI code as possible out of the work thread. The work threads logic is also rather complicated as
    I am working with both a webAPI and a MySQL server, so keeping it all in its own class would be ideal)
    If a more thorough explanation of what I am trying to achieve would help please let me know.
    Any help with either solving the above problem, or suggestions for alternative ways I could get the class in the UI thread to do something when prompted by the 2nd class in the 2nd thread would be appreciated.
    Thanks :)

    If I follow the explanation, I think you can use MVVM Light messenger.
    You can install it using NuGet.
    Search on mvvm light libraries only.
    You right click solution in solution explorer and choose manage nugget...
    So long as you're not accessing ui stuff on these other threads.
    using GalaSoft.MvvmLight.Messaging;
    namespace wpf_Tester
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    public MainWindow()
    InitializeComponent();
    Messenger.Default.Register<String>(this, (action) => ReceiveString(action));
    private void ReceiveString(string msg)
    MessageBox.Show(msg);
    Dispatcher.BeginInvoke((Action)delegate()
    tb.Text = msg;
    private void Button_Click(object sender, RoutedEventArgs e)
    Task.Factory.StartNew(() => {
    Messenger.Default.Send<String>("Hello World");
    What the above does is start up a new thread - that startnew does that.
    It sends of message of type string which the main window has subscribed to....it gets that and puts up a message box.
    The message is sent from the window to the window in that but this will work across any classes in a solution.
    Note that the receive acts on whichever thread the message is sent from.
    I would usually be altering properties of a viewmodel with such code which have no thread affinity.
    If you're then going to directly access properties of ui elements then you need to use Dispatcher.BeginInvoke to get back to the UI thread.
    I do that with an anonymous action in that bit of code but you can call a method or whatever instead if your logic is more complicated or you need it to be re-usable.
    http://social.technet.microsoft.com/wiki/contents/articles/26070.aspx
    Hope that helps.
    Technet articles: Uneventful MVVM;
    All my Technet Articles

  • Help calling JNI function from a java thread

    I am using the following code to call a JNI fuction from a java thread:
    public class CMSMessageHandler extends MessageHandler{
    static{
    System.loadLibrary("jastb");
    public native int cmsReadIt(ByteBuffer buff);
    private ByteBuffer dirbuf = null;
    /** Creates a new instance of CMSMessageHandler */
    public CMSMessageHandler() {
    // allocate to max size datagram
    dirbuf = ByteBuffer.allocateDirect(65536);
    public void readMessages(){
    /*Thread worker = new Thread(){
    public void run(){*/
    int count;
    while (true){
    try{
    count = cmsReadIt(dirbuf);
    } catch (Exception e){
    e.printStackTrace();
    worker.start();*/
    public static void main(String[] args) {
    CMSMessageHandler handler = new CMSMessageHandler();
    handler.readMessages();
    When I run this main method with the thread commented out, it works great. When I run the main method with the thread, it works great for a while, and then funny things start happening with the native library I am using. My native library uses shared memory, signals, and semaphores. It feels a bit like my java program is stomping on the resources that my native library is using, when a run the java program with a thread.
    Is there something I don't know about calling native code from a thread? Should I be doing something explicitly to protect my native library's shared memory, signals, or semaphores?
    Thanks,
    Lisa.

    Does the library do any initialization when loaded? Does it make a dangerous assumption that the thead calling cmdReadIt will always be the same thread that initially loaded it? Try loading the library in the worker thread instead of in the main thread via the static initializer.Yes. There is a call to another native method cmsOpenIt that does CMS initialization. I put cmsOpenIt as well as the System.loadLibrary("jastb") in the worker thread and I'm still experiencing the same problems.
    Incidently, the mere presence of another Thread in this program does not seem to cause problems. It's only when I run calls to cmsReadIt in a thread that I get into trouble.
    For example, this works fine:
    public class CMSMessageHandler extends MessageHandler{
        public native int cmsReadIt(ByteBuffer buff);
        public ByteBuffer dirbuf = null;
        static {
            System.loadLibrary("jastb");
        public CMSMessageHandler() {
            // allocate to max size datagram
            dirbuf = ByteBuffer.allocateDirect(65536);
        public void readMessages(){
            try{
                int count = 0;
                while (true){
                    count = cmsReadIt(dirbuf);
            } catch (Exception e){
        public static void main(String[] args) {
            CMSMessageHandler handler = new CMSMessageHandler();
            Thread worker = new Thread(){
                public void run(){
                    while (true){
                        try{
                            Thread.currentThread().sleep(1000);
                            System.out.println("sleep thread.");
                        } catch (Exception e){
                            e.printStackTrace();
            worker.start();
            handler.readMessages();  
        }Are there JVM flags that I should experiment with that might help mitigate/diagnose this problem?

  • Calling getAppletContext() from a working thread.

    Hi guys,
    I'm new to Java so all apologies if I'm asking a stupied question.
    I have a simple applet that creates a working thread and I'm tring to call getAppletContext() from that thread.
    Obviously my working thread has no instance of the Applet class so it fails.
    I've try to create an instance of Applet, but I'm getting an error saying that the applet is not initialised.
    This is my code:
    class MyThread extends Thread
        String ThreadName;
        public MyThread(String threadName)
            ThreadName = threadName;
        @Override public void run()
            // ??? How to make the following line work ???
            getAppletContext().showDocument(new URL("javascript:alert(\"Calling from myThread\")"));
    public class MyApplet extends Applet {
         public void init()
            // The following line works!
            getAppletContext().showDocument(new URL("javascript:alert(\"Calling from MyApplet)"));
            Thread WorkingThread = new MyThread("Thread1");                                                                
            WorkingThread.start();
    }{code}
    Please help,
    Many thanks!
    Salvador                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Got it.
    I needed to pass the keyword this to the thread constructor and then use that....
    Many thanks!

Maybe you are looking for

  • Restore previous app/music after rebuilding library

    I recently chaged drive location to all my music (23000+ mp3) on my pc: ie: from D:\music to E:\music To avoid adding again all the music from scratches to iTunes I decided to just rebuild the library after mass-modifying the paths in the xml file (i

  • ABAP OO Events

    Dear all: In ABAP OO programming, Events can be raised to announce a change of state (or action etc) and the associated Event Handlers can react to that. SAP says that after the Event is raised: - caller program halts processing - all subscribed Even

  • Bulletin Board Theme Transitions

    Does anyone know why the transitions for the Bulletin Board theme, the transitions aren't of one of the Photo Album transitions. And if so, how they can be changed globally to one of the four Photo Album transitions? I'm using iMovie 09 Thanks, Peter

  • Where's All My music gone?? Nooooo

    Hi, Any help here will be more than appreciated. My 30gb Ipod photo, had been playing up for a little while, by that I mean, it used to skip songs a lot and used to come up with that sad icon or folder icon. Then one day, it decided to completely los

  • Macbook Pro - Two extra displays? Help!

    I currently have a 17" 4:3 Dell monitor connected to my MBP at my desk. I would also like to connect a 32" 16:9 TV as well, without having to change connections every time I switch. I thought about getting a DVI splitter, but I feel like there would