Skip to content

Commit bbd3e36

Browse files
committed
Fix the issue that if winrt_callback_client destruct before connect returns, it will be access violation.
1 parent e83d8b9 commit bbd3e36

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

Release/src/websockets/client/ws_client_winrt.cpp

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,17 +175,26 @@ class winrt_callback_client : public websocket_client_callback_impl, public std:
175175
m_msg_websocket->MessageReceived += ref new TypedEventHandler<MessageWebSocket^, MessageWebSocketMessageReceivedEventArgs^>(m_context, &ReceiveContext::OnReceive);
176176
m_msg_websocket->Closed += ref new TypedEventHandler<IWebSocket^, WebSocketClosedEventArgs^>(m_context, &ReceiveContext::OnClosed);
177177

178-
return pplx::create_task(m_msg_websocket->ConnectAsync(uri)).then([=](pplx::task<void> result) -> pplx::task<void>
178+
std::weak_ptr<winrt_callback_client> thisWeakPtr = shared_from_this();
179+
return pplx::create_task(m_msg_websocket->ConnectAsync(uri)).then([thisWeakPtr](pplx::task<void> result) -> pplx::task<void>
179180
{
180181
try
181182
{
183+
// result.get() should happen before anything else, to make sure there is no unobserved exception
184+
// in the task chain.
182185
result.get();
183-
m_messageWriter = ref new DataWriter(m_msg_websocket->OutputStream);
186+
187+
std::shared_ptr<winrt_callback_client> pThis(thisWeakPtr.lock());
188+
if (pThis == nullptr)
189+
{
190+
throw websocket_exception("Websocket client is being destroyed");
191+
}
192+
193+
pThis->m_messageWriter = ref new DataWriter(m_msg_websocket->OutputStream);
184194
}
185195
catch (Platform::Exception^ e)
186196
{
187-
websocket_exception exc(e->HResult, build_error_msg(e, "ConnectAsync"));
188-
return pplx::task_from_exception<void>(exc);
197+
throw websocket_exception(e->HResult, build_error_msg(e, "ConnectAsync"));
189198
}
190199
return pplx::task_from_result();
191200
});

0 commit comments

Comments
 (0)