473,791 Members | 2,947 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
Jul 19 '05 #1
1 2283
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

Jul 19 '05 #2

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

Similar topics

1
4884
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
3419
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);
2
3077
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
9082
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
3
1965
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 event, and then the operation handling this event calls threaded object's dispose method. The problem is: If an exception is thrown the event is never raised, the operation never executes dispose and my resources get stuck on the memory until the app...
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
3597
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
1760
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
9515
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,...
0
10426
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10154
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
9993
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
9029
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...
0
5430
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4109
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
3713
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.