Asynhronious socket: block this thread before all data are sent

289 Views Asked by At

Regarding asynchronious sockets, I would like to know if its possible to hold the thread, before all the data are sent?

With use of Socket.BeginSend

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

I send data inside buffer parameter. I would like to know if is it possible to block the thread some how before all data are really sent from here (without regarding if data are received on the other side)? So I can call a Socket.BeginReceive method?

--

Will it be good enough to use a ManualResetEvent delegate (I called it "sendDone")?

Example:

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

Is this good enough? Or are there any better alterantives?

thx for the ans

1

There are 1 best solutions below

0
On

The easiest way is to use the Send method on the Socket class, as it blocks the calling thread, like so:

byte[] buffer = ...;

int bytesSent = socket.Send(bytes);

Note that if you really wanted to block on the call to BeginSend, you can use the Task Parallel Library to create a Task<TResult> which you can then wait on, like so:

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;