C#C# V4 Publish & Subscribe API Reference for Realtime Apps

Go to Configuration


 

These docs are for PubNub 4.0 for C# which is our latest and greatest! For the docs of the 3.x versions of the SDK, please check the links: C#, Windows 8, Windows 8.1, ASP.Net, Windows Phone 8, Windows Phone 8.1, Xamarin.iOS, Xamarin.Android, Xamarin.Mac and C# PCL.

If you have questions about the PubNub for C# SDK, please contact us at support@pubnub.com.

The Publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid PublishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
 
Publish Anytime
It is not required to be subscribed to a channel in order to publish to that channel.
Message Data:
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. Message data should not contain special C# V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Message Size:
The maximum number of characters per message is 32K by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5KB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details please check: https://support.pubnub.com/support/discussions/topics/14000006322

Message Publish Rate:
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber cannot keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels.
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably.
There are some best practices to ensure messages are delivered when publishing to a channel:
  • Publish to any given channel in a serial manner (i.e. not concurrently).
  • Check that the return code is success (e.g. [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.
 
Do Not JSON serialize!
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the C# V4 SDK:
  1. ParameterTypeRequiredDescription
    MessageobjectYesThe payload.
    ChannelstringYesDestination of the Message.
    ShouldStoreboolOptional

    Store in history.

    If ShouldStore is not specified, then the history configuration on the key is used.

    MetaDictionary<string, object>OptionalMeta data object which can be used with the filtering ability.
    UsePOSTboolOptionalUse POST to Publish.
    TtlintOptional
    Set a per message time to live in storage.
    1. If ShouldStore = true, and Ttl = 0, the message is stored with no expiry time.
    2. If ShouldStore = true and Ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
    3. If ShouldStore = false, the Ttl parameter is ignored.
    4. If Ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
    QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
    SyncCommandOptionalBlock the thread, exception thrown if something goes wrong.
    AsyncPNCallbackOptionalPNCallback of type PNPublishResult.

Publish a message to a channel:

//Publishing Dictionary
Dictionary<string, float> position = new Dictionary<string, float>();
position.Add("lat", 32F);
position.Add("lng", 32F);
 
Console.WriteLine("before pub: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(position));
 
pubnub.Publish()
    .Message(position)
    .Channel("my_channel")
    .Async(new PNPublishResultExt(
        (result, status) => {
            Console.WriteLine("pub timetoken: " + result.Timetoken.ToString());
            Console.WriteLine("pub status code : " + status.StatusCode.ToString());
        }
    ));
 
Before running the above publish example, either using the Debug Console, or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
The Publish() operation returns a PNPublishResult which contains the following parameter:
Property NameTypeDescription
TimetokenlongReturns a long representation of the time token when the message was published.
  1. string[] arrayMessage = new string[] { 
        "hello",
        "there"
    };
     
    pubnub.Publish()
        .Message(arrayMessage.ToList())
        .Channel("suchChannel")
        .ShouldStore(true)
        .Meta("<json data as dictionary object>")
        .UsePOST(true)
        .Async(new PNPublishResultExt(
            (result, status) => {
                // handle publish result, status always present, result if successful
                // status.Error to see if error happened
            }
        ));
  2. PNPublishResult res = pubnub.Publish()
        .Channel("coolChannel")
        .Message("test")
        .ShouldStore(true)
        .Ttl(10)
        .Sync();
  3. PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.PublishKey = "my_pubkey";
    pnConfiguration.SubscribeKey = "my_subkey";
    pnConfiguration.CipherKey = "my_cipherkey";
    pnConfiguration.Secure = true;
     
    Pubnub pubnub = new Pubnub(pnConfiguration);
    
    string[] arrayMessage = new string[] { 
        "hello", 
        "there"
    };
    
    /***Publish same example what we already have. Repeating below***/
    pubnub.Publish()
        .Message(arrayMessage.ToList())
        .Channel("my_channel")
        .ShouldStore(true)
        .UsePOST(true)
        .Async(new PNPublishResultExt(
            (result, status) => {
                // Check whether request successfully completed or not.
                if (status.Error) {
                    // something bad happened.
                    Console.WriteLine("error happened while publishing: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status));
                } else {
                    Console.WriteLine("publish worked! timetoken: " + result.Timetoken.ToString());
                }
            }
        ));
  4. public class MobilePayload
    {
        public Dictionary<string, object> pn_apns;
        public Dictionary<string, object> pn_gcm;
        public Dictionary<string, object> pn_mpns;
        public Dictionary<string, object> full_game;
    }
    
    
    Dictionary<string, object> apnsData = new Dictionary<string, object>();
    apnsData.Add("aps", new Dictionary<string, object>() {
        { "alert", "Game update 49ers touchdown" },
        { "badge", 2 }
    });
    apnsData.Add("teams", new string[] { "49ers", "raiders" });
    apnsData.Add("score", new int[] { 7, 0 });
    
    Dictionary<string, object> gcmData = new Dictionary<string, object>();
    gcmData.Add("data", new Dictionary<string, object>() {
        { 
            "summary", "Game update 49ers touchdown"
        },
        { 
            "teams", new string[]{ "49ers", "raiders"}
        },
        {
            "score", new int[]{ 7, 0}
        },
        {
            "lastplay", "5yd run up the middle"
        },
    });
    
    Dictionary<string, object> mpnsData = new Dictionary<string, object>();
    mpnsData.Add("type", "flip");
    mpnsData.Add("title", "Front title");
    mpnsData.Add("count", 1);
    mpnsData.Add("back_title", "Back Tile");
    mpnsData.Add("back_content", "Back message");
    
    MobilePayload mobilePayload = new MobilePayload();
    mobilePayload.pn_apns = apnsData;
    mobilePayload.pn_gcm = gcmData;
    mobilePayload.pn_mpns = mpnsData;
    mobilePayload.full_game = new Dictionary<string, object>() {
        { "date","2014.05.20" },
        { "foobar","Data that is not pertinent to devices" }
    };
    
    
    pubnub.Publish()
        .Message(mobilePayload)
        .Channel("my_channel")
        .ShouldStore(true)
        .Async(new PNPublishResultExt(
            (result, status) => {
                // Check whether request successfully completed or not.
                if (status.Error) {
                    // something bad happened.
                    Console.WriteLine("error happened while publishing: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status));
                } else {
                    Console.WriteLine("publish worked! timetoken: " + result.Timetoken.ToString());
                }
            }
        ));
    For more details please refer Mobile Push Gateway Tutorial.
The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the C# V4 SDK:
  1. ParameterTypeRequiredDescription
    MessageobjectYesThe payload.
    ChannelstringYesDestination of the message.
    MetaDictionary<string, object>OptionalMeta data object which can be used with the filtering ability.
    UsePOSTboolOptionalUse POST to Publish.
    QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
    SyncCommandOptionalBlock the thread, exception thrown if something goes wrong.
    AsyncPNCallbackOptionalPNCallback of type PNPublishResult

Fire a message to a channel:

string[] arrMessage = new string[] { 
    "hello",
    "there"
};
 
pubnub.Fire()
    .Message(arrMessage.ToList())
    .Channel(channel)
    .UsePOST(true)
    .Async(new PNPublishResultExt(
        (result, status) => {
            if (status.Error) {
            	// something bad happened.
            	Console.WriteLine("error happened while publishing: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status));
            } else {
            	Console.WriteLine("publish worked! timetoken: " + result.Timetoken.ToString());
            }
        }
    ));
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate SubscribeKey at initialization.
By default a newly subscribed client will only receive messages published to the channel after the Subscribe() call completes.
If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period. This can be achieved by setting ReconnectionPolicy to PNReconnectionPolicy.LINEAR, when initializing the client.
 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Subscribe to a channel you can use the following method(s) in the C# V4 SDK:
  1. ParameterTypeRequiredDescription
    ChannelsArrayOptionalSubscribe to Channels, Either Channels or ChannelGroups is required.
    ChannelGroupsArrayOptionalSubscribe to ChannelGroups, Either Channels or ChannelGroups is required.
    WithTimetokenlongOptionalPass a Timetoken.
    WithPresenceCommandOptionalAlso subscribe to related presence information.
    QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
    ExecuteCommandYesCommand that will Execute Subscribe.
Subscribe to a channel:
pubnub.Subscribe<string>()
    .Channels(new string[] {
        // subscribe to channels
        "my_channel" 
     })
    .Execute();
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
 

PNMessageResult<T> is returned in the Listeners.

The Subscribe() operation returns a PNStatus which contains the following operations:
Property NameTypeDescription
Category PNStatusCategoryDetails of PNStatusCategory are here.
Error boolThis is true if an error occurred in the execution of the operation.
ErrorData PNErrorDataError data of the exception (if Error is true)
StatusCode intStatus code of the excution.
Operation PNOperationTypeOperation type of the request.
AffectedChannels List<string>A list of affected channels in the operation.
AffectedChannelGroups List<string>A list of affected channel groups in the operation.
The Subscribe() operation returns a PNMessageResult<T> for messages which contains the following operations:
Property NameTypeDescription
MessageobjectThe message sent on the channel.
SubscriptionstringThe channel group or wildcard subscription match (if exists).
ChannelstringThe channel for which the message belongs.
TimetokenlongTimetoken for the message.
UserMetadataobjectUser metadata.
The Subscribe() operation returns a PNPresenceEventResult from presence which contains the following operations:
Property NameTypeDescription
EventstringEvents like join, leave, timeout, state-change, interval.
UuidstringUUID for the event.
TimestamplongTimestamp for the event.
OccupancyintCurrent occupancy.
StateDictionaryState of the UUID.
SubscriptionstringThe channel group or wildcard subscription match (if exists).
ChannelstringThe channel for which the message belongs.
TimetokenlongTimetoken of the message.
UserMetadataobjectUser metadata.
Joinstring[]List of channels when the event is interval.
Timeoutstring[]List of channels when the event is interval.
Leavestring[]List of channels when the event is interval.
HereNowRefreshboolFlag to indicate whether HereNow fetch is needed.
  1. PNConfiguration pnConfiguration = new PNConfiguration();
    // subscribeKey from admin panel
    pnConfiguration.SubscribeKey = "my_subkey"; // required
    // publishKey from admin panel (only required if publishing)
    pnConfiguration.PublishKey = "my_pubkey";
    // secretKey (only required for access operations)
    pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
    Pubnub pubnub = new Pubnub(pnConfiguration);
    
    pubnub.Subscribe<string>()
        .Channels(new string[] {
            // subscribe to channels
            "my_channel"
        }) 
        .Execute();
  2. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    pubnub.Subscribe<string>()
        .Channels(new string[] { 
            // subscribe to channels information
            "my_channel1",
            "my_channel2" 
        })
        .Execute();
  3. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.
    pubnub.Subscribe<string>()
        .Channels(new string[] {
            // subscribe to channels
            "my_channel" 
        })
        .WithPresence() // also subscribe to related presence information
        .Execute();
    {
        "Event": "join",
        "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "Timestamp": 1345546797,
        "Occupancy": 2,
        "State": null,
        "Channel":" my_channel",
        "Subscription": "",
        "Timetoken": 15034141109823424,
        "UserMetadata": null,
        "Join": null,
        "Timeout": null,
        "Leave": null,
        "HereNowRefresh": false
    }
    
    {
        "Event": "leave",
        "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "Timestamp": 1345546797,
        "Occupancy": 1,
        "State": null,
        "Channel": "my_channel",
        "Subscription": "",
        "Timetoken": 15034141109823424,
        "UserMetadata": null,
        "Join": null,
        "Timeout": null,
        "Leave": null,
        "HereNowRefresh": false
    }
    {
        "Event": "timeout",
        "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "Timestamp": 1345546797,
        "Occupancy": 0,
        "State": null,
        "Channel": "my_channel",
        "Subscription": "",
        "Timetoken": 15034141109823424,
        "UserMetadata": null,
        "Join": null,
        "Timeout": null,
        "Leave": null,
        "HereNowRefresh": false
    }
    
    {
        "Event": "state-change",
        "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "Timestamp": 1345546797,
        "Occupancy": 1,
        "State": {
            "isTyping": true
        },
        "Channel": "my_channel",
        "Subscription": "",
        "Timetoken": 15034141109823424,
        "UserMetadata": null,
        "Join": null,
        "Timeout": null,
        "Leave": null,
        "HereNowRefresh": false
    }
    
    {
        "Event": "interval",
        "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "Timestamp": 1345546797,
        "Occupancy": 2,
        "State": null,
        "Channel": "my_channel",
        "Subscription": "",
        "Timetoken": 15034141109823424,
        "UserMetadata": null,
        "Join": null,
        "Timeout": null,
        "Leave": null,
        "HereNowRefresh": false
    }
    

    When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

    • joined
    • left
    • timedout

    For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

    {
        "Event": "interval",
        "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "Timestamp": <unix timestamp>,
        "Occupancy": <# users in channel>,
        "State": null,
        "Channel": "my_channel",
        "Subscription": "",
        "Timetoken": 15034141109823424,
        "UserMetadata": null,
        "Join": ["uuid2", "uuid3"],
        "Timeout": ["uuid1"],
        "Leave": null,
        "HereNowRefresh": false
    }
    

    If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

    {
        "Event": "interval",
        "Uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "Timestamp": <unix timestamp>,
        "Occupancy": <# users in channel>,
        "State": null,
        "Channel": "my_channel",
        "Subscription": "",
        "Timetoken": 15034141109823424,
        "UserMetadata": null,
        "Join": null,
        "Timeout": null,
        "Leave": null,
        "HereNowRefresh": true
    }
    
  4. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).
     
    3 levels (2 dots) of wildcarding is supported, e.g.:
    a.*
    a.b.*
    pubnub.Subscribe<string>()
        .Channels(new string[] { 
            // subscribe to channels information
            "foo.*" 
        })
        .Execute();
  5. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.SubscribeKey = "demo";
    pnConfiguration.PublishKey = "demo";
    Pubnub pubnub = new Pubnub(pnConfiguration);
    pubnub.AddListener(new SubscribeCallbackExt(
        (pubnubObj, message) => {  },
        (pubnubObj, presence) => {  },
        (pubnubObj, status) => {
            if (status.Category == PNStatusCategory.PNConnectedCategory) {
                Dictionary<string, object> data = new Dictionary<string, object>();
                data.Add("FieldA", "Awesome");
                data.Add("FieldB", 10);
    
                pubnub.SetPresenceState()
                    .Channels(new string[] { "awesomeChannel" })
                    .ChannelGroups(new string[] { "awesomeChannelGroup" })
                    .State(data)
                    .Async(new PNSetStateResultExt(
                        (r, s) => {
                            // handle set state response
                        }
                    ));
            }
        }
    ));
    
    pubnub.Subscribe<string>()
        .Channels(new string[] {
            "awesomeChannel"
        }) 
        .Execute();
  6. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.Subscribe<string>()
        .Channels(new string[] {
            // subscribe to channels
            "ch1",
            "ch2"
        }) 
        .ChannelGroups(new string[] {
            // subscribe to channel groups
            "cg1",
            "cg2"
        }) 
        .WithTimetoken(1337L) // optional, pass a timetoken
        .WithPresence() // also subscribe to related presence information
        .Execute();
  7. Requires Stream Controller and Presence add-on XRequires that both Stream Controller and Presence add-ons are enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.Subscribe<string>()
        .ChannelGroups(new string[] {
            // subscribe to channel groups
            "cg1",
            "cg2"
        }) 
        .WithTimetoken(1337L) // optional, pass a timetoken
        .WithPresence() // also subscribe to related presence information
        .Execute();
  8. C# V4 supports subscribing with custom types. However only one type of message can be subscribed for a given channel. If you want to subscribe different types of messages for the same channel, then subscribing using the generic type as string is the recommended option.
    public class Phone
        {
            public string Number { get; set; }
            public string Extenion { get; set; }
    
            [JsonConverter(typeof(StringEnumConverter))]
            public PhoneType PhoneType { get; set; }
        }
    
        public enum PhoneType
        {
            Home,
            Mobile,
            Work
        }
    
    
    Phone myPhone = new Phone() { 
        Number = "111-222-2222",
        PhoneType = PhoneType.Mobile,
        Extenion = "11"
    };
    
    pubnub.Publish()
        .Message(myPhone)
        .Channel("my_channel")
        .ShouldStore(true)
        .Async(new PNPublishResultExt(
            (result, status) => {
                // Check whether request successfully completed or not.
                if (status.Error) {
                    // something bad happened.
                    Console.WriteLine("error happened while publishing: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status));
                } else {
                    Console.WriteLine("publish worked! timetoken: " + result.Timetoken.ToString());
                }
            }
        ));
    
    
    SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
        (pubnubObj, message) => 
    	{ 
    		//message.Message gives the Phone object because you subscribed to type Phone during subscribe.
    	},
        (pubnubObj, presence) => { },
        (pubnubObj, status) => { });
     
    pubnub.AddListener(listenerSubscribeCallack);
    pubnub.Subscribe<Phone>()
        .Channels(new string[] {        
            "my_channel" // subscribe to channels
         })
        .Execute();
    
    
    //If you are subscribing to multiple message types, then 
    
    SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
        (pubnubObj, message) => 
    	{ 
    		//message.Message gives the string object because you subscribed to type "string" during subscribe.
    		string phoneStringMessage = m.Message.ToString(); //this is your string message
                    Phone myMsg = new Phone();
                    pubnub.JsonPluggableLibrary.PopulateObject(phoneStringMessage, myMsg); //using Json.Net library. You can directly use Json.Net library calls if you wish
    	},
        (pubnubObj, presence) => { },
        (pubnubObj, status) => { });
     
    pubnub.AddListener(listenerSubscribeCallack);
    pubnub.Subscribe<string>()
        .Channels(new string[] {        
            "my_channel" // subscribe to channels
         })
        .Execute();
When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.
 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Unsubscribe from a channel you can use the following method(s) in the C# V4 SDK
  1. ParameterTypeRequiredDescription
    ChannelsArrayOptionalUnsubscribe to channels, Either Channels or ChannelGroups is required
    ChannelGroupsArrayOptionalUnsubscribe to channel groups, Either channels or channelGroup is required
    QueryParamDictionary<string, object>OptionalDictionary object to pass name/value pairs as query string params with PubNub URL request for debug purpose.
    ExecuteCommandYesCommand that will execute Unsubscribe.
Unsubscribe from a channel:
pubnub.Unsubscribe<string>()
     .Channels(new string[] {
        "my_channel"
     })
     .Execute();
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
The Unsubscribe() operation returns a PNStatus. The output below demonstrates the response to a successful call:
{
    "Category": "PNDisconnectedCategory",
    "ErrorData": null,
    "Error": false,
    "StatusCode": 200,
    "Operation": "PNUnsubscribeOperation",
    "TlsEnabled": false,
    "Uuid": null,
    "AuthKey": null,
    "Origin": "ps.pndsn.com",
    "ClientRequest": null,
    "AffectedChannels": ["my_channel"],
    "AffectedChannelGroups": []
}
  1. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.Unsubscribe<string>()
        .Channels(new string[] { 
            "ch1",
            "ch2", 
            "ch3" 
        })
        .ChannelGroups(new string[] {
            "cg1", 
            "cg2", 
            "cg3" 
        })
        .Execute();
    {
        "Category": "PNDisconnectedCategory",
        "ErrorData": null,
        "Error": false,
        "StatusCode": 200,
        "Operation": "PNUnsubscribeOperation",
        "TlsEnabled": false,
        "Uuid": null,
        "AuthKey": null,
        "Origin": "ps.pndsn.com",
        "ClientRequest": null,
        "AffectedChannels": ["ch1","ch2","ch3"],
        "AffectedChannelGroups": ["cg1","cg2","cg3"]
    }
    
  2. pubnub.Unsubscribe<string>()
        .ChannelGroups(new string[] {
            "cg1",
            "cg2",
            "cg3"
        })
        .Execute();
    {
        "Category": "PNDisconnectedCategory",
        "ErrorData": null,
        "Error": false,
        "StatusCode": 200,
        "Operation": "PNUnsubscribeOperation",
        "TlsEnabled": false,
        "Uuid": null,
        "AuthKey": null,
        "Origin": "ps.pndsn.com",
        "ClientRequest": null,
        "AffectedChannels": [],
        "AffectedChannelGroups": ["cg1","cg2","cg3"]
    }
    
Unsubscribe from all channels and all channel groups
pubnub.UnsubscribeAll<string>();
None

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
    (pubnubObj, message) => { 
        // Handle new message stored in message.Message 
    },
    (pubnubObj, presence) => { 
        // handle incoming presence data 
    },
    (pubnubObj, status) => {
        // the status object returned is always related to subscribe but could contain
        // information about subscribe, heartbeat, or errors
        // use the PNOperationType to switch on different options
        switch (status.Operation) {
            // let's combine unsubscribe and subscribe handling for ease of use
            case PNOperationType.PNSubscribeOperation:
            case PNOperationType.PNUnsubscribeOperation:
                // note: subscribe statuses never have traditional
                // errors, they just have categories to represent the
                // different issues or successes that occur as part of subscribe
                switch (status.Category) {
                    case PNStatusCategory.PNConnectedCategory:
                        // this is expected for a subscribe, this means there is no error or issue whatsoever
                    break;
                    case PNStatusCategory.PNReconnectedCategory:
                        // this usually occurs if subscribe temporarily fails but reconnects. This means
                        // there was an error but there is no longer any issue
                    break;
                    case PNStatusCategory.PNDisconnectedCategory:
                        // this is the expected category for an unsubscribe. This means there
                        // was no error in unsubscribing from everything
                    break;
                    case PNStatusCategory.PNUnexpectedDisconnectCategory:
                        // this is usually an issue with the internet connection, this is an error, handle appropriately
                    break;
                    case PNStatusCategory.PNAccessDeniedCategory:
                        // this means that PAM does allow this client to subscribe to this
                        // channel and channel group configuration. This is another explicit error
                    break;
                    default:
                        // More errors can be directly specified by creating explicit cases for other
                        // error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory`
                    break;
                }
            break;
            case PNOperationType.PNHeartbeatOperation:
                // heartbeat operations can in fact have errors, so it is important to check first for an error.
                if (status.Error) {
                    // There was an error with the heartbeat operation, handle here
                } else {
                    // heartbeat operation was successful
                }
            break;
            default:
                // Encountered unknown status type
            break;
        }
    });

pubnub.AddListener(listenerSubscribeCallack);
SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
    (pubnubObj, message) => { },
    (pubnubObj, presence) => { },
    (pubnubObj, status) => { });

pubnub.AddListener(listenerSubscribeCallack);

// some time later
pubnub.RemoveListener(listenerSubscribeCallack);
CategoryDescription
PNNetworkIssuesCategoryThe SDK is not able to reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy.
PNUnknownCategoryPubNub SDK could return this Category if the captured error is insignificant client side error or not known type at the time of SDK development.
PNBadRequestCategoryPubNub C# SDK will send PNBadRequestCategory when some parameter is missing like subscribe key, publish key.
PNTimeoutCategoryProcessing has failed because of request time out.
PNReconnectedCategory
SDK was able to reconnect to pubnub.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).

Go to Presence