簡體   English   中英

異步套接字:在發送所有數據之前阻塞此線程

[英]Asynhronious socket: block this thread before all data are sent

關於asynchronious sockets ,我想知道在發送所有數據之前是否有可能保持線程?

使用Socket.BeginSend

public IAsyncResult BeginSend(
byte[] buffer,
int offset,
int size,
SocketFlags socketFlags,
AsyncCallback callback,
Object state

我在緩沖區參數內發送數據。 我想知道是否有可能在真正從此處發送所有數據之前如何阻塞線程(而不考慮是否在另一側接收到數據)? 所以我可以調用Socket.BeginReceive方法嗎?

-

使用ManualResetEvent委托(我稱其為“ sendDone”)是否足夠好?

例:

 private static ManualResetEvent sendDone = new ManualResetEvent(false);
 //inisde a method call WaitOne() method:
 sendDone.WaitOne();

這樣夠好嗎? 還是有更好的替代品?

謝謝

最簡單的方法是在Socket上使用Send方法 ,因為它阻塞了調用線程,如下所示:

byte[] buffer = ...;

int bytesSent = socket.Send(bytes);

請注意,如果你真的想在調用BeginSend塊,你可以使用任務並行庫創建Task<TResult>然后你就可以等待,就像這樣:

Task<int> task = Task.Factory.FromAsync(
    socket.BeginSend(buffer, offset, size, socketFlags, null, null), 
    socket.EndSend);

// Wait on the task.
task.Wait();

// Get the result.
// Note, you can omit the call to wait above, the call to 
// Result will block.
int bytesSent = task.Result;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM