Getting Started#

pckg_version
license
downloads

Introduction#

_images/icon.png

RsSmw is a C# NuGet package for remote control of Rohde & Schwarz SMW200A Vector Signal Generators. It offers a fixed API derived from the instrument’s SCPI structure, so you call methods instead of typing command strings. That gives you auto-completion and helps you avoid the string-typing mistakes that everyone who works with SCPI knows well.

The basic idea:
SCPI command: SYSTem:REFerence:FREQuency:SOURce 10e6

C# calls:
writing: driver.System.Reference.Frequency.Source = IntExtEnum.INTernal
reading: IntExtEnum value = driver.System.Reference.Frequency.Source

Couple of reasons why to choose this module over plain SCPI approach:

  • Type-safe API

  • You can still use the plain SCPI communication

  • You can select which VISA to use or even not use any VISA at all

  • Initialization of a new session is straightforward, no need to set any other properties

  • Many useful features are already implemented - reset, self-test, opc-synchronization, error checking, option checking

  • Binary data blocks transfer in both directions

  • Transfer of arrays of numbers in binary or ASCII format

  • File transfers in both directions

  • Events generation in case of error, sent data, received data, chunk data (in case of big data transfer)

  • Logging

  • Multithreading session locking - you can use multiple threads talking to one instrument at the same time

Installation#

RsSmw is hosted on NuGet.org. You can install it from the Visual Studio NuGet Package Manager, or from the Package Manager Console:

PM> Install-Package RsSmw

Preconditions

  • Installed VISA. You can skip this if you plan to use only socket LAN connection. Download the Rohde & Schwarz VISA for Windows, Linux, Mac OS from here

Finding Available Instruments#

RsSmw can search for available instruments:

// Find instruments in your environment

using System;
using System.Collections.Generic;
using System.Linq;
// Install as NuGet package from www.nuget.org repository
using RohdeSchwarz.RsSmw;

namespace RsSmw_FindInstrument
{
    partial class Program
    {
        static void Main()
        {
            // Use the instrList items later as resource names in the RsSmw constructor
            IEnumerable<string> instrList = RsSmw.FindResources("?*");
            instrList.ToList().ForEach(Console.WriteLine);
        }
    }
}

If you have more VISAs installed, the one actually used by default is defined by a secret widget called VISA Conflict Manager. You can force your program to use R&S VISA:

// Find any USB instruments in your environment with the VISA preference

using System;
using System.Collections.Generic;
using System.Linq;
// Install as NuGet package from www.nuget.org
using RohdeSchwarz.RsSmw;

namespace RsSmw_FindInstrument
{
    partial class Program
    {
        static void Main()
        {
            // 'vxi11' and 'lxi' boolean arguments have only effect for R&S VISA
            // As 'plugin' you can use:
            // - 'NativeVisa' (default system VISA)
            // - 'RsVisa' (Rohde & Schwarz VISA)
            // - 'RsVisaPrio' (Prefer Rohde & Schwarz VISA, fall back to default VISA)
            string plugin = "RsVisa";
            var instrList = RsSmw.FindResources("USB?*", false, false, plugin);
            instrList.ToList().ForEach(Console.WriteLine);
        }
    }
}

Tip

We believe our R&S VISA is the best choice for our customers. Here are the reasons why:

  • Small footprint

  • Superior VXI-11 and HiSLIP performance

  • Integrated legacy sensors NRP-Zxx support

  • Additional VXI-11 and LXI devices search

  • Availability for Windows, Linux, Mac OS

Initiating instrument session#

RsSmw offers four different types of starting your remote-control session. We begin with the most typical case, and progress with more special ones.

Standard Session Initialization

A new instrument session starts when you instantiate the RsSmw object. Below is a Hello World example. The resource names are examples for different physical interfaces.

// Hello World example for a RsSmw

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_HelloWorld
{
    partial class Program
    {
        static void Main()
        {
            // Standard LAN connection (also called VXI-11)
            var resourceString1 = "TCPIP::192.168.2.100::INSTR";
            // Hi-Speed LAN connection - see 1MA208
            var resourceString2 = "TCPIP::192.168.2.100::hislip0";
            // GPIB Connection
            var resourceString3 = "GPIB::20::INSTR";
            // USB-TMC (Test and Measurement Class)
            var resourceString4 = "USB::0x0AAD::0x0119::022019943::INSTR";
            // R&S Powersensor NRP-Z86 (needs NRP-Toolkit installed)
            var resourceString5 = "RSNRP::0x0095::104015::INSTR";

            // Initializing the session
            RsSmw instr = new RsSmw(resourceString1);

            // Shortcut to the utility members
            var utils = instr.Utilities;
            Console.WriteLine("RsSmw Driver Version: " + utils.Identification.DriverVersion);
            Console.WriteLine("Visa Manufacturer: " + utils.Identification.VisaManufacturer);
            Console.WriteLine("Instrument Full Name: " + utils.Identification.InstrumentFullName);
            Console.WriteLine("Installed Options: " + string.Join(",", utils.Identification.InstrumentOptions));
            string idn = utils.QueryString("*IDN?");
            Console.WriteLine("\nHello, I am: " + idn);

            Console.WriteLine("\nPress any key ...");
            Console.ReadKey();

            // Close the session
            instr.Dispose();
        }
    }
}

Note

If you are wondering about the missing ASRL1::INSTR, yes, it works too.

RsSmw applies the necessary session settings for each interface. After the session is open, the identification properties are available on instr.Utilities.Identification:

  • string IdnString

  • Version DriverVersion

  • string VisaManufacturer

  • string InstrumentFullName

  • string InstrumentSerialNumber

  • string InstrumentFirmwareVersion

  • IEnumerable<string> InstrumentOptions

The constructor also contains optional boolean arguments idQuery and resetDevice:

bool idQuery = true;
bool resetDevice = true;
RsSmw instr = new RsSmw("TCPIP::192.168.2.100::hislip0", idQuery, resetDevice);
  • Setting idQuery to true (default is true) checks whether your instrument can be used with the RsSmw module.

  • Setting resetDevice to true (default is false) performs an instrument reset. The constructor always calls Utilities.DefaultInstrumentSetup() after the session is open. Utilities.Reset() performs that same reset and setup.

Selecting Specific VISA

Just like in the static method FindResources(), RsSmw allows you to prefer R&S VISA:

// Open your instrument with preferred Rohde & Schwarz VISA

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_VisaSelect
{
    partial class Program
    {
        static void Main()
        {
            var resourceString = "TCPIP::192.168.2.100::INSTR";
            // Force use of the Rs Visa. For default system VISA, use the "SelectVisa=NativeVisa"
            RsSmw instr = new RsSmw(resourceString, true, false, "SelectVisa=RsVisa");

            string idn = instr.Utilities.QueryString("*IDN?");
            Console.WriteLine("\nHello, I am: " + idn);
            Console.WriteLine("\nI am using VISA from " + instr.Utilities.Identification.VisaManufacturer);

            Console.WriteLine("\nPress any key ...");
            Console.ReadKey();

            // Close the session
            instr.Dispose();
        }
    }
}

No VISA Session

We recommend using VISA whenever possible, preferably with HiSlip session because of its low latency. However, if you are a strict VISA denier, RsSmw has something for you too - no Visa installation raw LAN socket:

// Using RsSmw without VISA for LAN Raw socket communication

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RohdeSchwarz.RsSmw;

namespace RsSmw_NoVisa
{
    partial class Program
    {
        static void Main()
        {
            var resourceString = "TCPIP::192.168.2.100::5025::SOCKET";  // SOCKET-like resource name
            RsSmw instr = new RsSmw(resourceString, true, false, "SelectVisa=SocketIo");
            string idn = instr.Utilities.QueryString("*IDN?");
            Console.WriteLine("\nHello, I am: " + idn);

            Console.WriteLine("\nNo VISA has been harmed or even used in this example.");
            Console.WriteLine("Press any key ...");
            Console.ReadKey();

            // Close the session
            instr.Dispose();
        }
    }
}

Warning

Not using VISA can cause problems by debugging when you want to use the communication Trace Tool. The good news is, you can easily switch to use VISA and back just by changing the constructor arguments. The rest of your code stays unchanged.

Simulating Session

If a colleague is currently occupying your instrument, leave him in peace, and open a simulating session:

var instr = new RsSmw("TCPIP::192.168.2.100::hislip0", true, false, "Simulate=True");

More optionString tokens are separated by comma:

var optionString = "SelectVisa=RsVisa, Simulate=True";
var instr = new RsSmw("TCPIP::192.168.2.100::hislip0", true, false, optionString);

Shared Session

In some scenarios, you want to have two independent objects talking to the same instrument. Rather than opening a second VISA connection, share the same one between two or more RsSmw objects:

// Sharing the same physical VISA session by two different RsSmw objects

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_SharedSession
{
    partial class Program
    {
        static void Main()
        {
            var instr1 = new RsSmw("TCPIP::192.168.2.100::INSTR");
            var instr2 = new RsSmw(instr1.Session);

            Console.WriteLine("instr1: " + instr1.Utilities.Identification.IdnString);
            Console.WriteLine("instr2: " + instr2.Utilities.Identification.IdnString);

            // Closing the instr2 session does not close the instr1 session.
            // instr1 is the 'session master'
            instr2.Dispose();
            Console.WriteLine("instr2: I am closed now");

            Console.WriteLine("instr1: I am still open and working.");
            Console.WriteLine("Look, I can prove it: " + instr1.Utilities.Identification.IdnString);

            instr1.Dispose();
            Console.WriteLine("instr1: Only now I am closed.");

            Console.WriteLine("\nPress any key ...");
            Console.ReadKey();
        }
    }
}

Note

The instr1 is the object holding the ‘master’ session. If you call the instr1.Dispose(), the instr2 loses its instrument session as well, and becomes pretty much useless.

Plain SCPI Communication#

After you have opened the session, you can use the instrument-specific part described in the RsSmw API Structure. If for any reason you want to use the plain SCPI, use the Utilities interface. The complete interface is described in Utilities. Its two basic methods are:

  • WriteString() - writing a command without an answer, for example *RST

  • QueryString() - querying your instrument, for example the *IDN? query

You may ask a question. Actually, two questions:

  • Q1: Why are they not called Write() and Query()?

  • Q2: Where is the Read() ?

Answer 1: Actually, there are: Write() = WriteString() and Query() = QueryString(), they are aliases. To avoid mixing string and binary communication, we promote the ones with String names. All the method names for binary transfer contain Bin in their names.

Answer 2: Short answer - you do not need it. Long answer - your instrument never sends unsolicited responses. If you send a set-command, you use WriteString(). For a query-command, you use QueryString(). So, you really do not need it…

Bottom line: if you are used to Write() and Query() methods, the WriteString() and QueryString() are their equivalents.

Enough with the theory, let us look at an example. Simple write and query:

// Basic string WriteString / QueryString

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_BasicScpiIo
{
    partial class Program
    {
        static void Main()
        {
            RsSmw instr = new RsSmw("TCPIP::192.168.2.100::INSTR");
            instr.Utilities.WriteString("*RST");
            var response = instr.Utilities.QueryString("*IDN?");
            Console.WriteLine(response);

            Console.WriteLine("\nPress any key ...");
            Console.ReadKey();

            // Close the session
            instr.Dispose();
        }
    }
}

This example is a so-called “University-Professor-Example” — good to show a principle, but never used in practice. The commands above are already part of the driver’s API. Here is another example, achieving the same goal:

// Basic string WriteString / QueryString

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_BasicScpiIo
{
    partial class Program
    {
        static void Main()
        {
            RsSmw instr = new RsSmw("TCPIP::192.168.2.100::INSTR");
            instr.Utilities.Reset();
            Console.WriteLine(instr.Utilities.Identification.IdnString);

            Console.WriteLine("\nPress any key ...");
            Console.ReadKey();

            // Close the session
            instr.Dispose();
        }
    }
}

One additional feature we need to mention here: VISA Timeout. VISA Timeout limits how long each QueryXxx() waits for an answer from the instrument. You can set and read it with Utilities.VisaTimeout. The value is in milliseconds:

// Timeout in milliseconds
instr.Utilities.VisaTimeout = 3000;

After this time, RsSmw raises a VisaTimeoutException. Instrument Status Checking is described in the next chapter.

Tip

Write() and Query() are already methods of Utilities, so you can call them directly:

instr.Utilities.Write("*RST");
var idn = instr.Utilities.Query("*IDN?");

For completion, we mention other string-based QueryXxx() methods, all in one example. They are convenient extensions providing type-safe double/boolean/integer querying features:

// Other query methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_TypedQueries
{
    partial class Program
    {
        static void Main()
        {
            RsSmw instr = new RsSmw("TCPIP::192.168.2.100::INSTR");
            instr.Utilities.VisaTimeout = 5000;
            instr.Utilities.InstrumentStatusChecking = true; // Default is true
            // Returning an integer
            int scount = instr.Utilities.QueryInteger("SWEEP:COUNT?");
            // Returning a boolean
            bool output = instr.Utilities.QueryBool("SOURCE:RF:OUTPUT:STATE?");
            // Returning a double
            double freq = instr.Utilities.QueryDouble("SOURCE:RF:FREQUENCY?");

            // Close the session
            instr.Dispose();
        }
    }
}

Lastly, a method providing basic synchronization: QueryOpc(). It sends query *OPC? to your instrument. The instrument waits with the answer until all the tasks it currently has in the execution queue are finished. This way your program waits too, and it is synchronized with actions in the instrument. Remember to have the VISA timeout set to an appropriate value to prevent the timeout exception. Here’s a snippet:

var oldTout = instr.Utilities.VisaTimeout;
instr.Utilities.VisaTimeout = 3000;
instr.Utilities.WriteString("INIT");
instr.Utilities.QueryOpc();
instr.Utilities.VisaTimeout = oldTout;

// The results are ready now to fetch
var results = instr.Utilities.QueryString("FETCH:MEASUREMENT?");

You can also specify the VisaTimeout just for one QueryOpc() call. QueryOpc(int) uses that timeout for the call and then restores the previous value. The following example is equivalent to the one above:

instr.Utilities.WriteString("INIT");
// Set the VISA Timeout for this call only, then set it back to the original value
instr.Utilities.QueryOpc(3000);

// The results are ready now to fetch
var results = instr.Utilities.QueryString("FETCH:MEASUREMENT?");

Tip

Wait, there’s more: you can send the *OPC? after each WriteString() automatically:

// Default value after init is false
instr.Utilities.OpcQueryAfterEachSetting = true;

Error Checking#

RsSmw has a built-in mechanism that after each command/query checks the instrument’s status subsystem, and throws an exception if it detects an error. For those who are already screaming: Speed Performance Penalty!!!, don’t worry, you can disable it.

Instrument status checking is very useful since in case your command/query caused an error, you are immediately informed about it. Status checking has in most cases no practical effect on the speed performance of your program. However, if for example, you do many repetitions of short write/query sequences, it might make a difference to switch it off:

// Default value after init is true
instr.Utilities.InstrumentStatusChecking = false;

To clear the instrument status subsystem of all errors, call this method:

instr.Utilities.ClearStatus();

Instrument’s status system error queue is clear-on-read. It means, if you query its content, you clear it at the same time. To query and clear list of all the current errors, use the following:

IEnumerable<string> errorsList = instr.Utilities.QueryAllErrors();

See the next chapter on how to react on write/query errors.

Exception Handling#

The base class for all the exceptions thrown by the RsSmw is RsSmwException. Inherited exception classes:

  • InstrumentStatusException thrown if a command or a query generated an error in the instrument’s error queue

  • VisaException thrown if the underlying VISA component throws an error

  • VisaTimeoutException thrown if the VISA timeout is reached. It is derived from OperationTimeoutException, so catch it first

  • OperationTimeoutException thrown if the OPC timeout is reached

In this example we show usage of all of them:

// How to deal with exceptions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_Exceptions
{
    partial class Program
    {
        static void Main()
        {
            RsSmw instr;
            try // Separate try-catch for initialization prevents accessing uninitialized object
            {
                // Adjust the VISA Resource string to fit your instrument
                instr = new RsSmw("TCPIP::192.168.2.100::INSTR");
            }
            catch (RsSmwException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Your instrument is probably OFF...");
                // Exit now, no point of continuing
                Console.WriteLine("Press any key to finish.");
                Console.ReadKey();
                return;
            }

            // Dealing with commands that potentially generate errors OPTION 1:
            // Switching the status checking OFF temporarily
            instr.Utilities.InstrumentStatusChecking = false;
            instr.Utilities.WriteString("MY:MISSpelled:COMMand");
            // Clear the error queue
            instr.Utilities.ClearStatus();
            // Status checking ON again
            instr.Utilities.InstrumentStatusChecking = true;

            // Dealing with queries that potentially generate errors OPTION 2:
            try
            {
                instr.Utilities.VisaTimeout = 1000;
                instr.Utilities.QueryString("MY:OTHEr:WRONg:QUERy?");
            }
            catch (InstrumentStatusException e)
            {
                // Instrument status error
                Console.WriteLine(e.Message);
                Console.WriteLine("Nothing to see here, moving on...");
            }
            catch (VisaException e)
            {
                // General Visa error
                Console.WriteLine(e.Message);
                Console.WriteLine("Somethin's seriously wrong...");
            }
            catch (VisaTimeoutException e)
            {
                // Visa Timeout error
                Console.WriteLine(e.Message);
                Console.WriteLine("That took a long time... longer than the VISA timeout");
            }
            catch (OperationTimeoutException e)
            {
                // OPC Timeout error
                Console.WriteLine(e.Message);
                Console.WriteLine("You called some method with OPC, and that took a long time...");
            }
            catch (RsSmwException e)
            {
                // General RsSmw error.
                // RsSmwException is a base class for all the RsSmw exceptions
                Console.WriteLine(e.Message);
                Console.WriteLine("Some other RsSmw error...");
            }
            finally
            {
                instr.Utilities.VisaTimeout = 5000;
                // Close the session in any case
                instr.Dispose();
            }
        }
    }
}

Tip

General rules for exception handling:

  • If you are sending commands that might generate errors in the instrument, for example deleting a file which does not exist, use the OPTION 1 - temporarily disable status checking, send the command, clear the error queue and enable the status checking again.

  • If you are sending queries that might generate errors or timeouts, for example querying measurement that cannot be performed at the moment, use the OPTION 2 - try/catch with optionally adjusting timeouts.

Transferring Files#

You just did a perfect measurement, saved the results as a screenshot to the instrument’s storage drive. Now you want to transfer it to your PC. With RsSmw, no problem, just figure out where the screenshot was stored on the instrument. In our case, it is var/user/instr_screenshot.png:

instr.Utilities.File.FromInstrumentToPc(
        @"var/user/instr_screenshot.png",
        @"c:\temp\pc_screenshot.png");

PC -> Instrument

Another common scenario: Your cool test program contains a setup file you want to transfer to your instrument: Here is the RsSmw one-liner split into three lines:

instr.Utilities.File.FromPcToInstrument(
        @"c:\MyCoolTestProgram\instr_setup.sav",
        @"var/appdata/instr_setup.sav");

Transferring Big Data with Progress#

We can agree that it can be annoying using an application that shows no progress for long-lasting operations. The same is true for remote-control programs. Luckily, the RsSmw has this covered. And, this feature is quite universal - not just for big files transfer, but for any data in both directions.

RsSmw allows you to register a handler, which it invokes after each transfer of one data chunk. You can set the chunk size, and you can slow the transfer down if you want to process the data as it arrives (direction instrument -> PC). The next example queries *IDN? with a chunk size of 2 bytes and a delay of 100 ms between each chunk read:

// Event handlers by reading - querying string data

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_ProgressEvent
{
    partial class Program
    {
        static void MyTransferHandler(object sender, InstrSegmentEventArgs args)
        {
            Console.Write("\nSegment: " + args.SegmentIx);
            Console.Write(", transferred bytes: " + args.TransferredSize);
            Console.Write(", total size: " + args.TotalSize);

            // Get the current segment data
            args.DataStream.Position = args.SegmentDataOffset;
            string text = new StreamReader(args.DataStream).ReadToEnd();
            Console.Write(", data: '" + text + "'");
            args.DataStream.Position = args.DataStream.Length;

            if (args.Finished)
            {
                Console.WriteLine("\n\nEnd of Transfer");
            }
            else
            {
                // Pause here for 100ms after each segment read
                Thread.Sleep(100);
            }
        }

        static void Main()
        {
            RsSmw instr = new RsSmw("TCPIP::192.168.2.100::INSTR");
            instr.Utilities.Events.ReadSegmentHandler = MyTransferHandler;
            // Set data chunk size to 2 bytes
            instr.Utilities.IoSegmentSize = 2;
            var response = instr.Utilities.QueryString("*IDN?");
            instr.Utilities.Events.ReadSegmentHandler = null;

            // Close the session
            instr.Dispose();
        }
    }
}

If you start it, args.TotalSize is -1. The driver does not know the size of the complete response up front, and an unknown size is reported as -1. For a transfer of known size, such as a file, TotalSize is the number of bytes. Calculate the progress only when TotalSize is greater than zero:

progress [pct] = 100 * args.TransferredSize / args.TotalSize

The following example transfers a file from instrument to the PC and back. In the callback, we skip showing the data, since it’s a quite big binary stream. Depending on the file size, adjust the IoSegmentSize and the Thread.Sleep() delay in the callback:

// Event handlers by reading - writing and reading big files

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_FileProgress
{
    partial class Program
    {
        static void MyRwHandler(object sender, InstrSegmentEventArgs args)
        {
            Console.Write("\nSegment: " + args.SegmentIx);
            Console.Write(", transferred bytes: " + args.TransferredSize);
            Console.Write(", total size: " + args.TotalSize);

            if (args.Finished)
            {
                Console.WriteLine("\n\nEnd of Transfer");
            }
            else
            {
                // Pause here for 1ms after each segment read
                Thread.Sleep(1);
            }
        }

        static void Main()
        {
            RsSmw instr = new RsSmw("TCPIP::192.168.2.100::INSTR");
            // Set data chunk size to 100 000 bytes
            instr.Utilities.IoSegmentSize = 100000;
            string pcFile = @"c:\temp\bigFile.bin";
            string pcFileBack = @"c:\temp\bigFileBack.bin";
            string instrFile = @"/var/user/bigFile.bin";

            Console.WriteLine("\n\nTransferring file from PC to the Instrument");

            instr.Utilities.Events.WriteSegmentHandler = MyRwHandler;
            instr.Utilities.File.FromPcToInstrument(pcFile, instrFile);
            instr.Utilities.Events.WriteSegmentHandler = null;

            Console.WriteLine("\n\nTransferring the file back from Instrument to the PC");

            instr.Utilities.Events.ReadSegmentHandler = MyRwHandler;
            instr.Utilities.File.FromInstrumentToPc(instrFile, pcFileBack);
            instr.Utilities.Events.ReadSegmentHandler = null;

            // Close the session
            instr.Dispose();
        }
    }
}

Multithreading#

You are at the party, many people talking over each other. Not every person can deal with such crosstalk, neither can measurement instruments. For this reason, RsSmw has a feature of scheduling the access to your instrument by using so-called Locks. Locks make sure that there can be just one client at a time ‘talking’ to your instrument. Talking in this context means completing one communication step - one command write or write/read or write/read/error check.

To describe how it works, and where it matters, we take two typical multithread scenarios:

One instrument session, accessed from multiple threads

You are all set — the lock is part of the instrument session. The following example sends 10 queries from parallel tasks. The session lock lets only one of them talk to the instrument at a time:

// Multiple threads are accessing one RsSmw object

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_Multithreading
{
    partial class Program
    {
        static void Main()
        {
            RsSmw instr = new RsSmw("TCPIP::192.168.2.100::INSTR");

            Parallel.For(1, 11,
                x =>
                {
                    Console.WriteLine("Query {0} started...", x);
                    var response = instr.Utilities.QueryString("*IDN?");
                    Console.WriteLine("...Query {0} finished.", x);
                });

            Console.WriteLine("\nPress any key ...");
            Console.ReadKey();

            // Close the session
            instr.Dispose();
        }
    }
}

More instrument sessions, accessed from multiple threads

We have two objects, instr1 and instr2 talking to the same instrument from multiple threads. The instr1 and instr2 objects have two independent locks. We bring them in sync with this call:

instr2.Utilities.AssignLock(instr1.Utilities.GetLock());

Check out the following example:

// Two RsSmw objects are used in multiple threads and are accessing the same instrument

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RohdeSchwarz.RsSmw;

namespace RsSmw_Multithreading
{
    partial class Program
    {
        static void Main()
        {
            RsSmw instr1 = new RsSmw("TCPIP::192.168.2.100::INSTR");
            RsSmw instr2 = new RsSmw(instr1.Session);
            instr1.Utilities.VisaTimeout = 200;
            // Synchronize the locks of both sessions
            instr2.Utilities.AssignLock(instr1.Utilities.GetLock());

            Parallel.For(1, 21,
                x =>
                {
                    if (x % 10 == 0)
                    {
                        // Multiples of 10 query instr1
                        Console.WriteLine("Instr1 {0} started...", x);
                        var response = instr1.Utilities.QueryString("*IDN?");
                        Console.WriteLine("...Instr1 Query {0} finished.", x);
                    }
                    else
                    {
                        // All other values query instr2
                        Console.WriteLine("Instr2 {0} started...", x);
                        var response = instr2.Utilities.QueryString("*IDN?");
                        Console.WriteLine("...Instr2 Query {0} finished.", x);
                    }
                });

            Console.WriteLine("\nPress any key ...");
            Console.ReadKey();

            // Close the sessions
            instr2.Dispose();
            instr1.Dispose();
        }
    }
}

Note

If you want to simulate some party crosstalk, delete this line:

instr2.Utilities.AssignLock(instr1.Utilities.GetLock());

Although the instr1 will still schedule its instrument access, the instr2 will be doing the same at the same time, which will then lead to all that fun stuff happening.