473,909 Members | 4,189 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Async behaviour in a thread

Hi all,

When using an asynchronous API call (in my case WriteFileEx) in a thread it
seems to become blocking instead of non-blocking (see details below). Can
somebody explain me what is happening here...

Details:
I wrote a simple program that is able to do very fast async writes to disk.
For that I used the WriteFileEx API call which is by nature asynchronous. At
first I wrote a simple console app to verify the concept, it worked fine.
Once integrated it in my main app, it became a lot slower. After
investigating a little, it seemed that the call became blocking instead of
non-blocking. The main difference between the console app and my main app is
that I put the calling method inside a worker thread. Does anybody know how
to fix this, make it async again ?

Kindest regards,

Tom

PS: My API call goes like this:

[DllImport("kern el32.dll", SetLastError=tr ue)]
public unsafe static extern int WriteFileEx ( IntPtr hFile,
byte[] lpBuffer,
int nNumberOfBytesT oWrite,
NativeOverlappe d * lpOverlapped,
IOCompletionCal lback lpCompletionRou tine);
Nov 16 '05 #1
2 2647
Any reason why you aren't using FileStream.Begi nRead for asynchronous IO?
I guess you are expecting an asynchronous WriteFile to be faster than a
synchronous one, however, I'm afraid this is not the case and it's not the
purpose of the API. This API is useful whenever you need to execute some
code after the call returns, but before the IO completes.
Anyway, without more details and some code that illustrates the problem,
it's hard to tell you why you see this different behavior.

Willy.

"Tom Vandeplas" <to***********@ agilent.com> wrote in message
news:10******** ******@cswreg.c os.agilent.com. ..
Hi all,

When using an asynchronous API call (in my case WriteFileEx) in a thread
it
seems to become blocking instead of non-blocking (see details below). Can
somebody explain me what is happening here...

Details:
I wrote a simple program that is able to do very fast async writes to
disk.
For that I used the WriteFileEx API call which is by nature asynchronous.
At
first I wrote a simple console app to verify the concept, it worked fine.
Once integrated it in my main app, it became a lot slower. After
investigating a little, it seemed that the call became blocking instead of
non-blocking. The main difference between the console app and my main app
is
that I put the calling method inside a worker thread. Does anybody know
how
to fix this, make it async again ?

Kindest regards,

Tom

PS: My API call goes like this:

[DllImport("kern el32.dll", SetLastError=tr ue)]
public unsafe static extern int WriteFileEx ( IntPtr hFile,
byte[] lpBuffer,
int nNumberOfBytesT oWrite,
NativeOverlappe d * lpOverlapped,
IOCompletionCal lback lpCompletionRou tine);

Nov 16 '05 #2
tom
Hi Willy

('t is toch altijd weer plezant om hier landgenoten terug te vinden ;-) )

I tried implementing the class using the different solutions .NET offers,
but in the end the one using WriteFileEx was really the fastest (according to
my tests, please convince me that I'm wrong, cause I don't like it
either...). The speed I'm aiming at is btw 150Mb/s on a SCSI Raid System...

The way I implemented it:

1) The File handle:
mFHandle = SystemAPI.Creat eFile(FileName,
FileAccess.Writ e,
FileShare.Write ,
0,
FileMode.Create ,
FILE_FLAG_OVERL APPED|FILE_FLAG _SEQUENTIAL_SCA N |
FILE_FLAG_NO_BU FFERING,
IntPtr.Zero);

As you can see I use the NO_BUFFERING option, this resulted in a significant
speed improvement... but it requires you to take sector sizes into account
(that's why I don't like it...)

2) Using the FilePointer I give the file it's final size (rounded to the
next sector size), to prevent the system resizing after every write...

3) The actual write routine:
internal unsafe void WriteBufferToDi sk(int Length)
{
IOCompletionCal lback _IOComp = new IOCompletionCal lback(IOComplet e);

Overlapped _ovl = new Overlapped();

_ovl.OffsetLow= mWritePtr;
_ovl.AsyncResul t = new myAsyncResult(m Indx);

mOvrlBuf[mIndx]=_ovl;

SystemAPI.Write FileEx(mFHandle ,mStreamingBuff ers[mIndx].Bytes,Length,m OvrlBuf[mIndx].Pack(_IOComp), _IOComp);

mIndx++;
mActiveWrites++ ;

if(mIndx==8)
mIndx=0;

mWritePtr+=Leng th;
}

You'll see something weird with the mOvrlBuf[], I agree... basically I keep
an array of Overlapped close, so I can do upto 8 writes "at the same time"
without having to look for the overlapped when finished... the array is
organized as a FIFO... This way I make sure the overlapped is never destroyed
before it's not needed anymore

4) The completion routine

private unsafe void IOComplete(uint Lo, uint Hi, NativeOverlappe d * NatOvrl)
{
Overlapped _ovl = Overlapped.Unpa ck(NatOvrl);

//int _indx = (int)_ovl.Async Result.AsyncSta te;

//I don't unpin, since my Streaming buffer handles this...
// UnPinBuffer(mGC Handles[_indx]);

Overlapped.Free (NatOvrl);
mActiveWrites--;
}

5) The pacing of the System happens using:

internal bool ReadyForData
{
get
{
return mActiveWrites<4 ;
}
}

I use a Async reset event at first.... but this "don't do it like this!"
method proved to be faster...

Anyway, as I said in my first post... once you put this in a thread it's not
async anymore. Any ideas ??

Kindest regards,

Tom

"Willy Denoyette [MVP]" wrote:
Any reason why you aren't using FileStream.Begi nRead for asynchronous IO?
I guess you are expecting an asynchronous WriteFile to be faster than a
synchronous one, however, I'm afraid this is not the case and it's not the
purpose of the API. This API is useful whenever you need to execute some
code after the call returns, but before the IO completes.
Anyway, without more details and some code that illustrates the problem,
it's hard to tell you why you see this different behavior.

Willy.

"Tom Vandeplas" <to***********@ agilent.com> wrote in message
news:10******** ******@cswreg.c os.agilent.com. ..
Hi all,

When using an asynchronous API call (in my case WriteFileEx) in a thread
it
seems to become blocking instead of non-blocking (see details below). Can
somebody explain me what is happening here...

Details:
I wrote a simple program that is able to do very fast async writes to
disk.
For that I used the WriteFileEx API call which is by nature asynchronous.
At
first I wrote a simple console app to verify the concept, it worked fine.
Once integrated it in my main app, it became a lot slower. After
investigating a little, it seemed that the call became blocking instead of
non-blocking. The main difference between the console app and my main app
is
that I put the calling method inside a worker thread. Does anybody know
how
to fix this, make it async again ?

Kindest regards,

Tom

PS: My API call goes like this:

[DllImport("kern el32.dll", SetLastError=tr ue)]
public unsafe static extern int WriteFileEx ( IntPtr hFile,
byte[] lpBuffer,
int nNumberOfBytesT oWrite,
NativeOverlappe d * lpOverlapped,
IOCompletionCal lback lpCompletionRou tine);


Nov 16 '05 #3

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

Similar topics

5
3267
by: Paul Hasell | last post by:
Hi, I'm trying to invoke a web method asynchronously but just can't seem to get it to tell me when it has finished! Below is the code I am (currently) using: private void btnUpload_Click(object sender, System.EventArgs e) { try { SOPWebService.Client uploader = new
6
3832
by: Shak | last post by:
Hi all, Three questions really: 1) The async call to the networkstream's endread() (or even endxxx() in general) blocks. Async calls are made on the threadpool - aren't we advised not to cause these to block? 2) You can connect together a binaryreader to a networkstream:
8
11033
by: Dinsdale | last post by:
I am trying to write a Tcp "Server" that opens a class that wraps a tcp socket when a new connection is made (Listener.AcceptSocket()). Everything is going swimmingly except when I try to close the socket during a read and I get the following error: <error_msg> An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in system.dll Additional information: The I/O operation has been aborted because of
11
8637
by: atlaste | last post by:
Hi, In an attempt to create a full-blown webcrawler I've found myself writing a wrapper around the Socket class in an attempt to make it completely async, supporting timeouts and some scheduling mechanisms. I use a non-blocking approach for this, using the call to 'poll' to support the async mechanism - rather than the 'begin' and 'end' functions. I already found that connecting doesn't set the "isconnected" variable correctly...
0
10035
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
11346
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...
1
11046
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,...
1
8097
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
7248
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5938
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...
0
6138
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4774
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
4336
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.