本文整理汇总了C#中IConnection.Stop方法的典型用法代码示例。如果您正苦于以下问题:C# IConnection.Stop方法的具体用法?C# IConnection.Stop怎么用?C# IConnection.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IConnection
的用法示例。
在下文中一共展示了IConnection.Stop方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CloseConnection
/// <summary> Close the given NMS Connection and ignore any thrown exception.
/// This is useful for typical <code>finally</code> blocks in manual NMS code.
/// </summary>
/// <param name="con">the NMS Connection to close (may be <code>null</code>)
/// </param>
/// <param name="stop">whether to call <code>stop()</code> before closing
/// </param>
public static void CloseConnection(IConnection con, bool stop)
{
if (con != null)
{
try
{
if (stop)
{
try
{
con.Stop();
}
finally
{
con.Close();
}
}
else
{
con.Close();
}
}
catch (NMSException ex)
{
logger.Debug("Could not close NMS Connection", ex);
}
catch (Exception ex)
{
// We don't trust the NMS provider: It might throw another exception.
logger.Debug("Unexpected exception on closing NMS Connection", ex);
}
}
}
示例2: ReleaseConnection
/// <summary>
/// Releases the given connection, stopping it (if necessary) and eventually closing it.
/// </summary>
/// <remarks>Checks <see cref="ISmartConnectionFactory.ShouldStop"/>, if available.
/// This is essentially a more sophisticated version of
/// <see cref="NmsUtils.CloseConnection(IConnection, bool)"/>
/// </remarks>
/// <param name="connection">The connection to release. (if this is <code>null</code>, the call will be ignored)</param>
/// <param name="cf">The ConnectionFactory that the Connection was obtained from. (may be <code>null</code>)</param>
/// <param name="started">whether the Connection might have been started by the application.</param>
public static void ReleaseConnection(IConnection connection, IConnectionFactory cf, bool started)
{
if (connection == null)
{
return;
}
if (started && cf is ISmartConnectionFactory && ((ISmartConnectionFactory)cf).ShouldStop(connection))
{
try
{
connection.Stop();
}
catch (Exception ex)
{
LOG.Debug("Could not stop NMS Connection before closing it", ex);
}
}
try
{
connection.Close();
} catch (Exception ex)
{
LOG.Debug("Could not close NMS Connection", ex);
}
}
示例3: VerifyLastActive
public static bool VerifyLastActive(IConnection connection)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
// Ensure that we have not exceeded the reconnect window
if (DateTime.UtcNow - connection.LastActiveAt >= connection.ReconnectWindow)
{
connection.Trace(TraceLevels.Events, "There has not been an active server connection for an extended period of time. Stopping connection.");
connection.Stop(new TimeoutException(String.Format(CultureInfo.CurrentCulture, Resources.Error_ReconnectWindowTimeout,
connection.LastActiveAt, connection.ReconnectWindow)));
return false;
}
return true;
}
示例4: NonDurableTopicSubscriber
public NonDurableTopicSubscriber(string topicName, string brokerUri, string clientId)
{
this.topicName = topicName;
this.connectionFactory = new ConnectionFactory(brokerUri);
this.connection = this.connectionFactory.CreateConnection();
try
{
this.connection.ClientId = clientId;
if (this.connection.IsStarted)
connection.Stop();
this.connection.Start();
this.session = connection.CreateSession();
ActiveMQTopic topic = new ActiveMQTopic(topicName);
this.consumer = this.session.CreateConsumer(topic, "2 > 1", false);
this.consumer.Listener += new MessageListener(OnMessage);
}
catch
{
}
}
示例5: OpenConnection
//.........这里部分代码省略.........
// Only raise the error event if we failed to reconnect
connection.OnError(exception);
Reconnect(connection, data);
}
}
}
else
{
IResponse response = task.Result;
Stream stream = response.GetResponseStream();
var eventSource = new EventSourceStreamReader(stream);
bool retry = true;
#if MONOTOUCH
lock(connection.Items)
{
#endif
connection.Items[EventSourceKey] = eventSource;
#if MONOTOUCH
}
#endif
eventSource.Opened = () =>
{
if (initializeCallback != null)
{
callbackInvoker.Invoke(initializeCallback);
}
if (reconnecting && connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
{
// Raise the reconnect event if the connection comes back up
connection.OnReconnected();
}
};
eventSource.Message = sseEvent =>
{
if (sseEvent.Type == EventType.Data)
{
if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
{
return;
}
bool timedOut;
bool disconnected;
ProcessResponse(connection, sseEvent.Data, out timedOut, out disconnected);
if (disconnected)
{
retry = false;
}
}
};
eventSource.Closed = exception =>
{
if (exception != null && !ExceptionHelper.IsRequestAborted(exception))
{
// Don't raise exceptions if the request was aborted (connection was stopped).
connection.OnError(exception);
}
// See http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.close.aspx
response.Close();
if (retry)
{
Reconnect(connection, data);
}
else
{
connection.Stop();
}
};
eventSource.Start();
}
});
if (errorCallback != null)
{
TaskAsyncHelper.Delay(ConnectionTimeout).Then(() =>
{
callbackInvoker.Invoke((conn, cb) =>
{
// Stop the connection
Stop(conn);
// Connection timeout occured
cb(new TimeoutException());
},
connection,
errorCallback);
});
}
}
示例6: PollingLoop
private void PollingLoop(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback, bool raiseReconnect = false)
{
string url = connection.Url;
// This is only necessary for the initial request where initializeCallback and errorCallback are non-null
int callbackFired = 0;
if (connection.MessageId == null)
{
url += "connect";
}
else if (raiseReconnect)
{
url += "reconnect";
if (!connection.ChangeState(ConnectionState.Connected, ConnectionState.Reconnecting))
{
return;
}
}
url += GetReceiveQueryString(connection, data);
#if NET35
Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "LP: {0}", (object)url));
#else
Debug.WriteLine("LP: {0}", (object)url);
#endif
_httpClient.PostAsync(url, PrepareRequest(connection)).ContinueWith(task =>
{
// Clear the pending request
connection.Items.Remove(HttpRequestKey);
bool shouldRaiseReconnect = false;
bool disconnectedReceived = false;
try
{
if (!task.IsFaulted)
{
if (raiseReconnect)
{
// If the timeout for the reconnect hasn't fired as yet just fire the
// event here before any incoming messages are processed
FireReconnected(connection);
}
// Get the response
var raw = task.Result.ReadAsString();
#if NET35
Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "LP Receive: {0}", (object)raw));
#else
Debug.WriteLine("LP Receive: {0}", (object)raw);
#endif
ProcessResponse(connection, raw, out shouldRaiseReconnect, out disconnectedReceived);
}
}
finally
{
if (disconnectedReceived)
{
connection.Stop();
}
else
{
bool requestAborted = false;
if (task.IsFaulted)
{
// Raise the reconnect event if we successfully reconnect after failing
shouldRaiseReconnect = true;
// Get the underlying exception
Exception exception = task.Exception.Unwrap();
// If the error callback isn't null then raise it and don't continue polling
if (errorCallback != null &&
Interlocked.Exchange(ref callbackFired, 1) == 0)
{
// Call the callback
errorCallback(exception);
}
else
{
// Figure out if the request was aborted
requestAborted = ExceptionHelper.IsRequestAborted(exception);
// Sometimes a connection might have been closed by the server before we get to write anything
// so just try again and don't raise OnError.
if (!requestAborted && !(exception is IOException))
{
// Raise on error
connection.OnError(exception);
// If the connection is still active after raising the error event wait for 2 seconds
// before polling again so we aren't hammering the server
TaskAsyncHelper.Delay(_errorDelay).Then(() =>
//.........这里部分代码省略.........
示例7: PollingLoop
private void PollingLoop(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback, bool raiseReconnect = false)
{
string url = connection.Url;
var reconnectTokenSource = new CancellationTokenSource();
int reconnectFired = 0;
// This is only necessary for the initial request where initializeCallback and errorCallback are non-null
int callbackFired = 0;
if (connection.MessageId == null)
{
url += "connect";
}
else if (raiseReconnect)
{
url += "reconnect";
}
url += GetReceiveQueryString(connection, data);
Debug.WriteLine("LP: {0}", (object)url);
_httpClient.PostAsync(url, PrepareRequest(connection), new Dictionary<string, string> { { "groups", GetSerializedGroups(connection) } }).ContinueWith(task =>
{
// Clear the pending request
connection.Items.Remove(HttpRequestKey);
bool shouldRaiseReconnect = false;
bool disconnectedReceived = false;
try
{
if (!task.IsFaulted)
{
if (raiseReconnect)
{
// If the timeout for the reconnect hasn't fired as yet just fire the
// event here before any incoming messages are processed
FireReconnected(connection, reconnectTokenSource, ref reconnectFired);
}
// Get the response
var raw = task.Result.ReadAsString();
Debug.WriteLine("LP Receive: {0}", (object)raw);
if (!String.IsNullOrEmpty(raw))
{
ProcessResponse(connection, raw, out shouldRaiseReconnect, out disconnectedReceived);
}
}
}
finally
{
if (disconnectedReceived)
{
connection.Stop();
}
else
{
bool requestAborted = false;
if (task.IsFaulted)
{
// Cancel the previous reconnect event
reconnectTokenSource.Cancel();
// Raise the reconnect event if we successfully reconnect after failing
shouldRaiseReconnect = true;
// Get the underlying exception
Exception exception = task.Exception.GetBaseException();
// If the error callback isn't null then raise it and don't continue polling
if (errorCallback != null &&
Interlocked.Exchange(ref callbackFired, 1) == 0)
{
// Raise on error
connection.OnError(exception);
// Call the callback
errorCallback(exception);
}
else
{
// Figure out if the request was aborted
requestAborted = IsRequestAborted(exception);
// Sometimes a connection might have been closed by the server before we get to write anything
// so just try again and don't raise OnError.
if (!requestAborted && !(exception is IOException))
{
// Raise on error
connection.OnError(exception);
// If the connection is still active after raising the error event wait for 2 seconds
// before polling again so we aren't hammering the server
TaskAsyncHelper.Delay(_errorDelay).Then(() =>
{
if (connection.IsActive)
//.........这里部分代码省略.........
示例8: CloseConnection
/// <summary>
/// Closes the given connection.
/// </summary>
/// <param name="con">The connection.</param>
protected virtual void CloseConnection(IConnection con)
{
if (LOG.IsDebugEnabled)
{
LOG.Debug("Closing shared NMS Connection: " + this.target);
}
try
{
try
{
if (this.started)
{
this.started = false;
con.Stop();
}
} finally
{
con.Close();
}
} catch (Exception ex)
{
LOG.Warn("Could not close shared NMS connection.", ex);
}
}
示例9: OpenConnection
//.........这里部分代码省略.........
}
if (reconnecting && !CancellationToken.IsCancellationRequested)
{
connection.State = ConnectionState.Reconnecting;
// Retry
Reconnect(connection, data);
return;
}
}
else
{
IResponse response = task.Result;
Stream stream = response.GetResponseStream();
var eventSource = new EventSourceStreamReader(stream);
bool retry = true;
// When this fires close the event source
CancellationToken.Register(() => eventSource.Close());
eventSource.Opened = () =>
{
if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
{
initializeCallback();
}
if (reconnecting)
{
// Change the status to connected
connection.State = ConnectionState.Connected;
// Raise the reconnect event if the connection comes back up
connection.OnReconnected();
}
};
eventSource.Error = connection.OnError;
eventSource.Message = sseEvent =>
{
if (sseEvent.Type == EventType.Data)
{
if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
{
return;
}
bool timedOut;
bool disconnected;
ProcessResponse(connection, sseEvent.Data, out timedOut, out disconnected);
if (disconnected)
{
retry = false;
}
}
};
eventSource.Closed = () =>
{
response.Close();
if (retry && !CancellationToken.IsCancellationRequested)
{
// If we're retrying then just go again
connection.State = ConnectionState.Reconnecting;
Reconnect(connection, data);
}
else
{
connection.Stop();
}
};
if (!CancellationToken.IsCancellationRequested)
{
eventSource.Start();
}
}
});
if (initializeCallback != null)
{
TaskAsyncHelper.Delay(ConnectionTimeout).Then(() =>
{
if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
{
// Stop the connection
Stop(connection);
// Connection timeout occured
errorCallback(new TimeoutException());
}
});
}
}
示例10: PollingLoop
private void PollingLoop(IConnection connection, string data, bool raiseReconnect)
{
var url = connection.Url;
var reconnectTokenSource = new CancellationTokenSource();
var reconnectFired = 0;
if (connection.MessageId == null)
url += "connect";
else if (raiseReconnect)
url += "reconnect";
url += GetReceiveQueryString(connection, data);
Debug.WriteLine(string.Format("LP: {0}", url));
var postData = new Dictionary<string, string> {{"groups", GetSerializedGroups(connection)}};
HttpClient.Post(url, connection.PrepareRequest, postData, true)
.ContinueWith(task =>
{
var response = task.Result;
// Clear the pending request
connection.Items.Remove(HttpRequestKey);
var shouldRaiseReconnect = false;
var disconnectedReceived = false;
try
{
if (response.Exception != null)
return;
// If the timeout for the reconnect hasn't fired as yet just fire the
// event here before any incoming messages are processed
if (raiseReconnect)
FireReconnected(connection, reconnectTokenSource, ref reconnectFired);
// Get the response
response.ReadAsString().ContinueWith(t =>
{
var raw = t.Result;
Debug.WriteLine(string.Format("LP Receive: {0}", raw));
if (!string.IsNullOrEmpty(raw))
ProcessResponse(connection, raw, out shouldRaiseReconnect, out disconnectedReceived);
});
}
finally
{
if (disconnectedReceived)
connection.Stop();
else
{
if (response.Exception != null)
{
// Cancel the previous reconnect event
reconnectTokenSource.Cancel();
// Get the underlying exception
var exception = response.Exception.GetBaseException();
// Figure out if the request was aborted
var requestAborted = IsRequestAborted(exception);
// Sometimes a connection might have been closed by the server before we get to write anything
// so just try again and don't raise OnError.
if (!requestAborted && !(exception is IOException))
{
// Raise on error
connection.OnError(exception);
// If the connection is still active after raising the error event wait for 2 seconds
// before polling again so we aren't hammering the server
Thread.Sleep(ErrorDelay);
if (connection.IsActive)
{
PollingLoop(connection, data, true);
}
}
}
else
{
// Continue polling if there was no error
if (connection.IsActive)
{
PollingLoop(connection, data, shouldRaiseReconnect);
}
}
}
}
});
if (!raiseReconnect)
return;
Thread.Sleep(ReconnectDelay);
// Fire the reconnect event after the delay. This gives the
FireReconnected(connection, reconnectTokenSource, ref reconnectFired);
//.........这里部分代码省略.........
示例11: PollingLoop
private void PollingLoop(IConnection connection, string data, System.Action initializeCallback, Action<Exception> errorCallback, bool raiseReconnect)
{
string _url = connection.Url;
var _reconnectTokenSource = new CancellationTokenSource();
int _reconnectFired = 0;
if (connection.MessageId == null)
_url += "connect";
else if (raiseReconnect)
_url += "reconnect";
_url += GetReceiveQueryString(connection, data);
//Debug.WriteLine("LongPollingTransport: PollingLoop for [{0}]", _url);
var _signal = m_httpClient.PostAsync(
_url,
PrepareRequest(connection),
new Dictionary<string, string> {
{ "groups", GetSerializedGroups(connection) }
});
_signal.Finished += (sender, e) =>
{
// Clear the pending request
connection.Items.Remove(c_httpRequestKey);
bool _shouldRaiseReconnect = false;
bool _disconnectedReceived = false;
try
{
if (!e.Result.IsFaulted)
{
if (raiseReconnect)
// If the timeout for the reconnect hasn't fired as yet just fire the
// event here before any incoming messages are processed
FireReconnected(connection, _reconnectTokenSource, ref _reconnectFired);
// Get the response
var _raw = e.Result.ReadAsString();
//Debug.WriteLine("LongPollingTransport: Receive [{0}]", _raw);
if (!String.IsNullOrEmpty(_raw))
ProcessResponse(connection, _raw, out _shouldRaiseReconnect, out _disconnectedReceived);
}
}
finally
{
if (_disconnectedReceived)
connection.Stop();
else
{
bool _requestAborted = false;
if (e.Result.IsFaulted)
{
// Cancel the previous reconnect event
_reconnectTokenSource.Cancel();
// Raise the reconnect event if we successfully reconnect after failing
_shouldRaiseReconnect = true;
// Get the underlying exception
Exception exception = e.Result.Exception.GetBaseException();
// If the error callback isn't null then raise it and don't continue polling
if (errorCallback != null)
{
// Raise on error
connection.OnError(exception);
// Call the callback
errorCallback(exception);
}
else
{
// Figure out if the request was aborted
_requestAborted = IsRequestAborted(exception);
// Sometimes a connection might have been closed by the server before we get to write anything
// so just try again and don't raise OnError.
if (!_requestAborted && !(exception is IOException))
{
// Raise on error
connection.OnError(exception);
// If the connection is still active after raising the error event wait for 2 seconds
// before polling again so we aren't hammering the server
Thread.Sleep(m_errorDelay);
if (connection.IsActive)
{
PollingLoop(
connection,
data,
null, // initializeCallback
null, // errorCallback
_shouldRaiseReconnect); // raiseReconnect
}
//.........这里部分代码省略.........
示例12: PollingLoop
private void PollingLoop(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback, bool raiseReconnect = false)
{
string url = connection.Url;
var reconnectTokenSource = new CancellationTokenSource();
int reconnectFired = 0;
if (connection.MessageId == null)
{
url += "connect";
}
url += GetReceiveQueryString(connection, data);
_httpClient.PostAsync(url, PrepareRequest(connection)).ContinueWith(task =>
{
// Clear the pending request
connection.Items.Remove(HttpRequestKey);
bool shouldRaiseReconnect = false;
bool disconnectedReceived = false;
try
{
if (!task.IsFaulted)
{
if (raiseReconnect)
{
// If the timeout for the reconnect hasn't fired as yet just fire the
// event here before any incoming messages are processed
FireReconnected(connection, reconnectTokenSource, ref reconnectFired);
}
// Get the response
var raw = task.Result.ReadAsString();
ProcessResponse(connection, raw, out shouldRaiseReconnect, out disconnectedReceived);
}
}
finally
{
if (disconnectedReceived)
{
connection.Stop();
}
else
{
bool requestAborted = false;
bool continuePolling = true;
if (task.IsFaulted)
{
// Cancel the previous reconnect event
reconnectTokenSource.Cancel();
// Raise the reconnect event if we successfully reconnect after failing
shouldRaiseReconnect = true;
// Get the underlying exception
Exception exception = task.Exception.GetBaseException();
// If the error callback isn't null then raise it and don't continue polling
if (errorCallback != null)
{
// Raise on error
connection.OnError(exception);
// Call the callback
errorCallback(exception);
// Don't continue polling if the error is on the first request
continuePolling = false;
}
else
{
// Figure out if the request was aborted
requestAborted = IsRequestAborted(exception);
// Sometimes a connection might have been closed by the server before we get to write anything
// so just try again and don't raise OnError.
if (!requestAborted && !(exception is IOException))
{
// Raise on error
connection.OnError(exception);
// If the connection is still active after raising the error event wait for 2 seconds
// before polling again so we aren't hammering the server
if (connection.IsActive)
{
Thread.Sleep(2000);
}
}
}
}
// Only continue if the connection is still active and wasn't aborted
if (continuePolling && !requestAborted && connection.IsActive)
{
PollingLoop(connection, data, null, null, shouldRaiseReconnect);
}
}
//.........这里部分代码省略.........
示例13: buttonValidate
//.........这里部分代码省略.........
TravelCost += afterPeak * rate1;
}
else
if ((IsTimeOfDayBetween(startTime, onpeak, offpeak)) && (IsTimeOfDayBetween(endTime, onpeak, offpeak)))
{
TravelCost += destTime * rate1;
}
else
TravelCost += destTime * rate2;
#endregion
//
// Price calculation logic
//
#region Message Queue
connectionFactory = new ConnectionFactory(BROKER, CLIENT_ID);
connection = connectionFactory.CreateConnection();
connection.Start();
session = connection.CreateSession();
subscriber = new Subscriber(session, TOPIC_NAME);
subscriber.Start(CONSUMER_ID);
subscriber.OnMessageReceived += new MessageReceivedDelegate(subscriber_OnMessageReceived);
using (var publisher = new Publisher(session, TOPIC_NAME))
{
publisher.SendMessage(TravelCost.ToString());
}
Thread.Sleep(1000);
try
{
subscriber.Dispose();
session.Close();
session.Dispose();
connection.Stop();
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
}
#endregion
//
// Rebate Processor
//
#region Rebate Processor
// Fetch membership class
conn.Open();
SqlDataReader rdr = null;
cmd = new SqlCommand("SELECT * FROM membership WHERE [email protected]", conn);
cmd.Parameters.AddWithValue("@Id", txtMemberId.Text);
rdr = cmd.ExecuteReader();
rdr.Read();
string memclass = rdr.GetString(3);
conn.Close();
// Obtain order status
conn.Open();
rdr = null;
cmd = new SqlCommand("SELECT * FROM booking WHERE [email protected]", conn);
cmd.Parameters.AddWithValue("@Id", txtMemberId.Text);
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
OrderExists = true;