2010-07-04 86 views
0

我使用通過發送大量的緩衝區有一個插座,即時通訊,如果生病做類似淨異步的Socket多線程發送

// may be accsed form a a lot of threads 
void Send(byte[] buffer) 
{ 
    m_socket.BeginSend(buffer ... , SendCallback); 
} 

void SendCallback() 
{ 
    m_socket.EndSend() 

    // if not done sending- send the reset 
    m_socket.BeginSend() 
} 

我的問題是:從一個多線程的立場來看這個工作,或者緩衝區會交錯嗎?

+0

你能對你正在使用的API更清晰?我沒有看到與您的調用相匹配的Socket.Send()重載。 – 2010-07-04 09:47:31

+0

對不起,函數名稱錯誤,編輯過。 im使用: \t \t public IAsyncResult BeginSend(byte [] buffer,int offset,int size,SocketFlags socketFlags,AsyncCallback callback,object state); – 2010-07-04 09:59:52

回答

0

引述MSDN:

如果一個套接字執行多個異步 操作,他們沒有 在它們開始在 的順序不一定完整。

但是,如果您要從多個線程發送數據塊,那麼您對'訂單'的定義是什麼呢?

+1

如果我有消息:「aaaa」和「bbbb」我不會讓reciver得到:「aaaabbbb」或「bbbbaaaa」,但不是「aabbaabb」,如果套接字的發送緩衝區是2個字節大。 – 2010-07-04 10:01:40

1

看來這是線程安全的。因爲你的委託給「SendCallback」是在一個新的線程上執行的,所以我會假定EndSend()可以根據當前的線程上下文來判斷你正在結束哪個異步操作。

請參閱MSDN的 「最佳實踐」 爲異步編程模型:

Simultaneously Executing Operations 

If your class supports multiple concurrent invocations, enable the developer to track each invocation separately by defining the MethodNameAsync overload that takes an object-valued state parameter, or task ID, called userSuppliedState. This parameter should always be the last parameter in the MethodNameAsync method's signature. 

http://msdn.microsoft.com/en-us/library/ms228974.aspx

+0

看看我對henk的評論 – 2010-07-04 11:19:15