473,406 Members | 2,312 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
Nov 15 '05 #1
2 3061
Hi Joshua,
That depends on the requirement.
you would like to do async only where you need the control to come back to
your code immediately and if the instruction to be executed next is not
dependant on the completion of the previous instruction.
Cheers
Benny

"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

Nov 15 '05 #2
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

Nov 15 '05 #3

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

Similar topics

1
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: 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...
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
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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,...

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.