IKernelLinkPacketArrived Event

Occurs when a MathLink packet arrives.

Definition

Namespace: Wolfram.NETLink
Assembly: Wolfram.NETLink (in Wolfram.NETLink.dll) Version: 2.0.0.0
C#
event PacketHandler PacketArrived

Value

PacketHandler

Remarks

Normal .NET/Link programs do not implement their own "packet loop", repeatedly calling NextPacket to read each packet and decide how to handle it. Instead, they use higher-level methods that handle the packet loop internally. These methods are WaitForAnswer, WaitAndDiscardAnswer, EvaluateToInputForm, EvaluateToOutputForm, EvaluateToImage, EvaluateToImageBytes, EvaluateToTypeset, and EvaluateToTypesetBytes. The internal packet loop discards all packets other than those that contain the result of the evaluation.

Sometimes, however, you want to see the intermediate packets that get sent. Examples of such packets are TextPackets containing output from the Wolfram Language Print function, and MessagePackets containing Wolfram Language warning messages. Seeing warning messages can be especially useful.

Rather than forcing you to write your own packet loop, .NET/Link fires the PacketArrived event every time a packet arrives from the Wolfram Language. You can install one or more handlers for this event and be able to inspect every packet that is sent.

Your event handler method(s) can consume or ignore the packet without affecting the internal packet loop in any way. You won't interfere with anything whether you read none, some, or all of the packet contents.

At the point that PacketArrived is fired, the packet has already been "opened" with NextPacket, so your handler can begin reading the packet contents immediately.

The PacketHandler event handler is passed two arguments: the link and the packet type.

Very advanced programmers can optionally indicate that the internal packet loop should not see the packet. This is done by returning false from your handler method. Normally, you will return true.

Example

Here is an example of installing a PacketArrived event handler that prints out the contents of all incoming packets. This can be very useful for debugging. In your program, add a line like this:
C#
// C#
ml.PacketArrived += new PacketHandler(PacketPrinterMethod);

// VB
AddHandler ml.PacketArrived, AddressOf PacketPrinterMethod
Elsewhere, the definition of PacketPrinterMethod:
C#
// C#
public static bool PacketPrinterMethod(IKernelLink ml, PacketType pkt) {
    Console.WriteLine("Packet of type {1} arrived. Its contents are: {2}", pkt, ml.PeekExpr());
    return true;
}

// VB
Public Shared Function PacketPrinterMethod(ByVal ml As IKernelLink, ByVal pkt As PacketType) As Boolean
    Console.WriteLine("Packet of type {1} arrived. Its contents are: {2}", pkt, ml.PeekExpr())
    Return True
End Function

See Also