473,406 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Synchronous call in Async method?

I am writing a class that includes several async methods following the
BeginXxx, EndXxx pattern. Some of these methods will call methods in the
framework such as Stream.Read or Socket.Send. Do I need to, or is it
recommended to use the async method calls instead (Stream.BeginRead, etc)?

Example:

MyMethod()
{
//...
Stream.Read();// I know this method requires parameters
//
// Should it be this instead?
// Stream.BeginRead();
// Stream.EndRead();
//...
}

BeginMyMethod()
{
}

EndMyMethod()
{
}

Thanks,
Josh
Jul 19 '05 #1
1 2250
Does this code look like it will work as expected for asynchronous
operations? Or, do my calls to stream.Read and socket.Send need to be
changed to stream.BeginRead and socket.BeginSend?

Thanks

// AsyncTest.cs

using System;

using System.Diagnostics;

using System.IO;

using System.Net;

using System.Net.Sockets;

using System.Text;

namespace JLCoady

{

public class AsyncTest

{

#region Fields

private int dataBufferSize = 512;

private int totalBytes;

#endregion

#region Properties
//--------------------------------------------------------------------------
---------

public int DataBufferSize

{

get { return dataBufferSize; }

set { dataBufferSize = value; }

}


//--------------------------------------------------------------------------
---------

public int TotalBytes

{

get { return totalBytes; }

}

#endregion

#region Constructors
//--------------------------------------------------------------------------
---------

public AsyncTest()

{

}

#endregion

#region Methods
//--------------------------------------------------------------------------
---------

private Socket OpenSocket(string hostName, int port)

{

if(hostName == null)

throw new ArgumentNullException("hostName");

Trace.WriteLine(

string.Format("{0}:{1}", hostName, port), "OpenSocket");

Socket result = null;

try

{

result = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,

ProtocolType.Tcp);

result.Connect(

new IPEndPoint(Dns.Resolve(hostName).AddressList[0], port));

}

catch(Exception exc)

{

CloseSocket(result);

throw new FtpException(string.Format(

"Could not connect to {0} on port {1}.", hostName, port),
exc);

}

return result;

}


//--------------------------------------------------------------------------
---------

private void CloseSocket(Socket socket)

{

Trace.WriteLine("CloseSocket");

if(socket != null && socket.Connected)

{

socket.Close();

socket = null;

}

}


//--------------------------------------------------------------------------
---------

public void Send(string hostName, int port, Stream stream)

{

if(hostName == null)

throw new ArgumentNullException("hostName");

if(stream == null)

throw new ArgumentNullException("stream");

Trace.WriteLine("Send");

totalBytes = 0;

byte[] buffer = new byte[DataBufferSize];

Socket socket = OpenSocket(hostName, port);

int bytes = stream.Read(buffer, 0, buffer.Length);

while(bytes > 0)

{

socket.Send(buffer, bytes, SocketFlags.None);

totalBytes += bytes;

bytes = stream.Read(buffer, 0, buffer.Length);

}

CloseSocket(socket);

}


//--------------------------------------------------------------------------
---------

private delegate void SendCallback(string hostName, int port, Stream
stream);

private SendCallback send;


//--------------------------------------------------------------------------
---------

public IAsyncResult BeginSend(string hostName, int port, Stream
stream,

AsyncCallback callback, object state)

{

if(hostName == null)

throw new ArgumentNullException("hostName");

if(stream == null)

throw new ArgumentNullException("stream");

Trace.WriteLine("BeginSend");

if(send == null)

send = new SendCallback(this.Send);

return send.BeginInvoke(hostName, port, stream, callback, state);

}


//--------------------------------------------------------------------------
---------

public void EndSend(IAsyncResult asyncResult)

{

if(asyncResult == null)

throw new ArgumentNullException("asyncResult");

Trace.WriteLine("EndSend");

if(!asyncResult.IsCompleted)

asyncResult.AsyncWaitHandle.WaitOne();

send.EndInvoke(asyncResult);

}

#endregion

}

}



"Joshua Coady" <jo**@coady.us> wrote in message
news:eH**************@tk2msftngp13.phx.gbl...
I am writing a class that includes several async methods following the
BeginXxx, EndXxx pattern. Some of these methods will call methods in the
framework such as Stream.Read or Socket.Send. Do I need to, or is it
recommended to use the async method calls instead (Stream.BeginRead, etc)?

Example:

MyMethod()
{
//...
Stream.Read();// I know this method requires parameters
//
// Should it be this instead?
// Stream.BeginRead();
// Stream.EndRead();
//...
}

BeginMyMethod()
{
}

EndMyMethod()
{
}

Thanks,
Josh

Jul 19 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Noel | last post by:
Hi, I am a tad confused about if there are any benefits from using asynchronous vs synchronous network communication. As my example, I have been writing a dns lookup stack with a network...
1
by: Chris | last post by:
Hi. I have a ibrary I'm trying to use via javascript within IE. This library uses an asynchronous model where I call into a function and pass it a callback function as one of its arguments. My...
9
by: David | last post by:
Hello I'm testing the XMLHttpRequest object in Firefox and IE. The code below works well in IE and Firefox. It shows "1" when the string is a number and "0" when not. The page aspxTest.aspx only...
2
by: Joshua Coady | last post by:
I am writing a class that includes several async methods following the BeginXxx, EndXxx pattern. Some of these methods will call methods in the framework such as Stream.Read or Socket.Send. Do I...
1
by: Sagaert Johan | last post by:
Hi I use an ocx on my form ,when i use a buttons click event to call a method on the ocx i have no problem. I made a Socket communication class that invokes an eventhandler through a...
15
by: Javier Estrada | last post by:
Can someone explaing the difference between these exception models regarding the structured exception handling? The documentation is not clear. Some code would actually help. Thx
3
by: Giovanni Bassi | last post by:
Hello Group, I am running an operation in a different thread. There are resources that are released when the thread is done running. This is done at the end of the execution as it raises an...
1
by: intrepid_dw | last post by:
All: I have prepared a .NET 1.1 client application that consumes a remote, public web service. All the functions work as expected, and, in general, the application has been successful for my...
3
by: KaNos | last post by:
Hi, "robot script pages" are html+javascript pages, can be played in aspx player. So in this tech, robot call aspx player's function (an interface is sheared) and wait a result synchronously with...
2
by: ng01 | last post by:
In AjaxPro, if you leave out the Callback parameter, it becomes a synchronous call. Is it possible to perform a synchronous call with ASP.NET AJAX? Please limit responses to the question...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.