473,695 Members | 1,716 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 2632
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
3254
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
3814
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
11014
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
8602
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
8562
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
9113
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
8830
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
6488
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
5837
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
4339
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
4575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2265
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1971
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.