Create and Destroy NI-DAQmx Tasks in Memory

Updated Jul 20, 2023

Reported In

Software

  • LabVIEW

Driver

  • NI-DAQmx

Issue Details

  • When is it appropriate to create and destroy tasks in the NI-DAQmx driver?
  • What are the implications to the memory of not destroying tasks after the acquisition is complete?
  • My code executes slowly if I use NI-DAQmx tasks in the loop.

Solution

The NI-DAQmx driver allocates and de-allocates the memory when a task is created and when a task is cleared, respectively. For example, if you have a DAQmx Create Task.vi inside a While Loop, a new task will be created on every iteration of the While Loop. If there is nothing limiting the speed of the While Loop, tasks will be created so quickly that LabVIEW will quickly run out of memory. It will also slow down loop iteration time affecting code performance.

You can prevent this by using the DAQmx Clear Task.vi. By clearing every task we create, we are allocating and deallocating memory correctly. Only tasks with unique names can be created so an easy way to prevent accidentally creating tasks in a loop is to name them. The DAQmx Create Task.vi will output an error if it tries to create a task that already exists.

Additional Information

The best practice is to create and destroy tasks outside of structures like For Loops or While Loops to avoid memory problems altogether. You can see this in action by looking through the shipping examples in the NI Example Finder

You can also let the NI-DAQmx driver manage its own de-allocation by enabling auto cleanup on the DAQmx Create Task.vi. If the auto cleanup parameter is set to true, the resources allocated in task creation will be freed when the VI completes. If auto cleanup is set to false, the resources will be freed when LabVIEW exits.