473,804 Members | 3,396 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.BeginRe ad, etc)?

Example:

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

BeginMyMethod()
{
}

EndMyMethod()
{
}

Thanks,
Josh
Nov 15 '05 #1
2 3077
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.u s> wrote in message
news:eH******** ******@tk2msftn gp13.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.BeginRe ad, etc)?

Example:

MyMethod()
{
//...
Stream.Read();// I know this method requires parameters
//
// Should it be this instead?
// Stream.BeginRea d();
// 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.BeginRea d and socket.BeginSen d?

Thanks

// AsyncTest.cs

using System;

using System.Diagnost ics;

using System.IO;

using System.Net;

using System.Net.Sock ets;

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(stri ng hostName, int port)

{

if(hostName == null)

throw new ArgumentNullExc eption("hostNam e");

Trace.WriteLine (

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

Socket result = null;

try

{

result = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am,

ProtocolType.Tc p);

result.Connect(

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

}

catch(Exception exc)

{

CloseSocket(res ult);

throw new FtpException(st ring.Format(

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

}

return result;

}


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

private void CloseSocket(Soc ket socket)

{

Trace.WriteLine ("CloseSocket") ;

if(socket != null && socket.Connecte d)

{

socket.Close();

socket = null;

}

}


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

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

{

if(hostName == null)

throw new ArgumentNullExc eption("hostNam e");

if(stream == null)

throw new ArgumentNullExc eption("stream" );

Trace.WriteLine ("Send");

totalBytes = 0;

byte[] buffer = new byte[DataBufferSize];

Socket socket = OpenSocket(host Name, port);

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

while(bytes > 0)

{

socket.Send(buf fer, bytes, SocketFlags.Non e);

totalBytes += bytes;

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

}

CloseSocket(soc ket);

}


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

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

private SendCallback send;


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

public IAsyncResult BeginSend(strin g hostName, int port, Stream
stream,

AsyncCallback callback, object state)

{

if(hostName == null)

throw new ArgumentNullExc eption("hostNam e");

if(stream == null)

throw new ArgumentNullExc eption("stream" );

Trace.WriteLine ("BeginSend" );

if(send == null)

send = new SendCallback(th is.Send);

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

}


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

public void EndSend(IAsyncR esult asyncResult)

{

if(asyncResult == null)

throw new ArgumentNullExc eption("asyncRe sult");

Trace.WriteLine ("EndSend");

if(!asyncResult .IsCompleted)

asyncResult.Asy ncWaitHandle.Wa itOne();

send.EndInvoke( asyncResult);

}

#endregion

}

}



"Joshua Coady" <jo**@coady.u s> wrote in message
news:eH******** ******@tk2msftn gp13.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.BeginRe ad, etc)?

Example:

MyMethod()
{
//...
Stream.Read();// I know this method requires parameters
//
// Should it be this instead?
// Stream.BeginRea d();
// 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
2284
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 need to, or is it recommended to use the async method calls instead (Stream.BeginRead, etc)? Example: MyMethod() { //...
1
4885
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 communication class switchable between asynchronous and synchronous. When I use asynchronous udp communication I find that if I want to process a large amount of dns lookups I have one dns provider with many state objects passing through (and a high...
1
3421
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 method returns immediately, and the callback function is called shortly thereafter... virtually immediately. I want to find a way to simplify my code by finding a way to simulate synchronous behavior for those functions. It's a little awkward...
9
17997
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 write "0" or "1" with a "response.write" method. The problem that I have is when I try this example with Synchronous mode. If I change the function sendNum with: xmlhttp.open("GET",url,false);
1
9083
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 delegate. If i call the ocx method in that handler i get that error.
15
3274
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
2021
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 purposes. I have discovered one bit of behavior that surprises me, however. At certain times, under heavy server-side loads, my calls to certain web service methods will time out on the *client* side (proxy timeout). My assumption was that the...
3
3598
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 a javascript method. I try it with GetCallbackEventReference but this tech works async. Could I use a javascript function with a sync call ? Thaks for responses,
2
1761
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 posed...let's leave the discussions of why not async, or what does the "A" mean for another thread. Thanks for any help and examples of how to do it.
0
9705
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9575
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10308
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10073
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9134
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7609
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5645
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4288
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3806
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.