473,657 Members | 2,540 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I cancel an asynchronous operation?

I'm writing a class that communicates with a server using the TcpClient
class. Most of the methods I've written are intended to be used
synchronously and will block until they are completed. But these calls will
be made very seldom and between operations I would like to put the client
into a "listening mode" that will listen for other server messages. When
the client is ready to send/receive data again, take it back out of
listening mode and again begin synchronous operations. It's quite easy to
set up a BeginRead on the stream I created and have its callback process any
messages received from the server. But when I want to STOP listening and
start synchronous operations again I need to be able to cancel this. I
think the easiest way would be if I could just cancel the thread that I
started the BeginRead operation on. I'm sure there is a way to use the
IAsyncResult or it's WaitHandle to cancel the thread, but threading is not
my strongpoint and a solution is alluding me right now. Any assistance
would be appreciated. Here's the skeleton of what I'm going for.

private IAsyncResult ar;

private void Listen()
{
listenBuffer = new byte[1024];
ar = stream.BeginRea d(listenBuffer, 0, listenBuffer.Le ngth, new
AsyncCallback(L istenMessage), this);
}
private void ListenMessage(I AsyncResult ar)
{
// ..... interpret received message.
}
private void StopListen()
{
// ?????? ar...
}


Any help is appreciated,
Jacob
Nov 15 '05 #1
3 11270
Jacob,
started the BeginRead operation on. I'm sure there is a way to use the
IAsyncResult or it's WaitHandle to cancel the thread, but threading is not
my strongpoint and a solution is alluding me right now. Any assistance
would be appreciated. Here's the skeleton of what I'm going for.


Unfortunately, cancelling the async. operations is not supported by the .NET
framework. I have recently had to write my own replacement since
cancellation was a must.

--
Dmitriy Lapshin [C# / .NET MVP]
X-Unity Test Studio
http://x-unity.miik.com.ua/teststudio.aspx
Bring the power of unit testing to VS .NET IDE

Nov 15 '05 #2
Well, that answers my question. Thanks for your help.

Jacob
"Dmitriy Lapshin [C# / .NET MVP]" <x-****@no-spam-please.hotpop.c om> wrote
in message news:ep******** ******@TK2MSFTN GP12.phx.gbl...
Jacob,
started the BeginRead operation on. I'm sure there is a way to use the
IAsyncResult or it's WaitHandle to cancel the thread, but threading is not my strongpoint and a solution is alluding me right now. Any assistance
would be appreciated. Here's the skeleton of what I'm going for.
Unfortunately, cancelling the async. operations is not supported by the

..NET framework. I have recently had to write my own replacement since
cancellation was a must.

--
Dmitriy Lapshin [C# / .NET MVP]
X-Unity Test Studio
http://x-unity.miik.com.ua/teststudio.aspx
Bring the power of unit testing to VS .NET IDE

Nov 15 '05 #3
On Mon, 29 Dec 2003 14:36:35 +0200, "Dmitriy Lapshin [C# / .NET MVP]"
<x-****@no-spam-please.hotpop.c om> wrote:
Jacob,
started the BeginRead operation on. I'm sure there is a way to use the
IAsyncResult or it's WaitHandle to cancel the thread, but threading is not
my strongpoint and a solution is alluding me right now. Any assistance
would be appreciated. Here's the skeleton of what I'm going for.


Unfortunatel y, cancelling the async. operations is not supported by the .NET
framework. I have recently had to write my own replacement since
cancellation was a must.


I am just researching this same problem. In my case, it's a server
socket that calls "BeginAccept()" . The MSDN doc sample "Using an
Asynchronous Server Socket" shows this code:

try {
listener.Bind(l ocalEP);
s.Listen(10); // <-- typo in MSDN docs!

while (true) {
allDone.Reset() ;

Console.WriteLi ne("Waiting for a connection...") ;
listener.BeginA ccept(
new AsyncCallback(S ocketListener.a cceptCallback),
listener );

allDone.WaitOne ();
}
} catch (Exception e) {
Console.WriteLi ne(e.ToString() );
}

An infinite loop of BeginAccept() calls is NOT what I would want in my
own server. As I have been trying to figure out how to cancel a
"pending" BeginAccept() call, I am finding out now that it can't be
done.

It's not too big a problem for me, as my own version has a way out of
the loop and closes the server socket. Either the server socket
closing OR the thread ending (which happens after the close) causes
the acceptCallback to be called ONCE the first time, and if I continue
hitting my server start and stop buttons, the acceptCallback will be
called TWICE everytime after that. Strange behaviour.

So I have been trying to figure out how to cancel the pending
BeginAccept() call. And now it seems it can't be done!

// CHRIS

Nov 15 '05 #4

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

Similar topics

1
7062
by: scott ocamb | last post by:
hello i am getting this error EndInvoke can only be called once for each asynchronous operation I have coded an app using the async method development pattern. This error occurred under stress testing
1
2092
by: Gopal Prabhakaran | last post by:
Dear Guys I developed a Win form application using C#. In my application, I used Login form to enter into application. In this login form I used three buttons( OK, Close and Cancel). The OK button call the web service and check the login credentails and then delivers the proper required data shown in the main screen back to the UI. Suppose I click the OK button, now I want to cancel the operation, so that I want to click the Cancel...
1
1326
by: RJN | last post by:
Hi I have 2 operations to perform one is to upload data and the second is to generate report. Both take huge time(more than 20 mins and I believe by that time session would have expired) and hence has to be done asynchronously. For uploading data, user will click start button and the asynchronous operation has to start immediately.
7
9703
by: Siv | last post by:
Hi, I have a stored procedure that I want to execute and then wait in a loop showing a timer whilst it completes and then carry on once I get notification that it has completed. The main reason for this being to stop the user thinking the application has frozen when in fact it is just waiting for a long SP to complete. Another reason for doing it like this is that I also have had a problem in the past where the SP takes longer than the...
2
4799
by: Robinson | last post by:
I can start an Asynchronous operation against a data source with SQLCommand.BeginExecuteReader, allowing me to loop, checking for user cancellation before the operation has completed, but how then to cancel the SQLCommand if the user wishes to? The "Cancel" method states: ".......... The Cancel method cannot be used to cancel a pending asynchronous operation." The scenario I'm thinking about here concerns a potentially long-running...
0
1750
by: Bishoy George | last post by:
Hi, I have a asp.net 2.0 web application. I want to implement the asynchronous model through http handler in web.config ------------------------------------------------------------------------------------------------------------------------- My web.config file: ---------------------
4
4072
by: Morgan Cheng | last post by:
Since ASP.NET 2.0, asynchronous web service client can be implemented with event-based pattern, instead of original BeginXXX/EndXXX pattern. However, I didn't find any material about event-based server side asynchronous web service. So, we can only implement asynchronous webmethod with BeginXXX/EndXXX pattern, right? I don't why ASP.NET 2.0 don't provide event-based server side pattern.
16
2425
by: parez | last post by:
I start a BackGroundWorker to populate a grid. It is started off in the ui layer The thread follows( cannot think of a better word) the path UI->Layer1->Layer2->Communication Layer and it blocks (the server is executing somthing where which takes time)
0
1157
by: karantech | last post by:
sir, can anybody plz give an easy explanation to me on how to cancel an asynchronous operation. i m using begininvoke, endinvoke async methods.
0
8326
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
7355
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
6177
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
5647
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
4173
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
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2745
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
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1736
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.