473,769 Members | 5,836 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Asynch crash when e.Cancel set?

Does anyone knmow why an asynchronous worker method would crash if the
e.Cancel method is set to true, but not otherwise?

I'm working on a demo app with an asynchronous call, using the .NET 2.0
BackgroundWorke r component. The app works fine if I let the worker method
proceed to completion. But if I cancel the worker method, it crashes.

Specifically, if I set the DoWorkEventArgs .Cancel property to true, the
worker thread crashes at the point where the worker method returns control
to the caller. If I set the Cancel flag to false, the operation is
cancelled, but the RunWorkerComple tedEventArgs.Ca ncelled property is wrong.

My worker method is called by the BackgroundWorke r_DoWork event handler,
which passes in a WidgetList, a reference to the background worker (which
DoWork cast from its sender argument), and the DoWork event arguments. Here
is the worker method code:

private WidgetList PopulateList(Wi dgetList sourceList, BackgroundWorke r
backgroundWorke r, DoWorkEventArgs e)
{
// Create deep copy (by serialization)
WidgetList resultList = sourceList.Deep Copy();

// Populate result list
for (int i = 0; i < 100; i++)
{
// Add new widget to the list
WidgetItem widget = new WidgetItem(i);
resultList.Add( widget);

// Pause to simulate slow process
Thread.Sleep(10 0);

// Check cancellation
if (backgroundWork er.Cancellation Pending)
{
// Set DoWork event args
e.Cancel = false;

// Return unmodified list
return sourceList;
}

// Report progress
backgroundWorke r.ReportProgres s(i);
}

// Set return value
return resultList;
}

And here is the exception I'm getting when the app stops:

System.Reflecti on.TargetInvoca tionException was unhandled
Message="Except ion has been thrown by the target of an invocation."
Source="mscorli b"
StackTrace:
at System.RuntimeM ethodHandle._In vokeMethodFast( Object target,
Object[] arguments, SignatureStruct & sig, MethodAttribute s methodAttribute s,
RuntimeTypeHand le typeOwner)
at System.RuntimeM ethodHandle.Inv okeMethodFast(O bject target,
Object[] arguments, Signature sig, MethodAttribute s methodAttribute s,
RuntimeTypeHand le typeOwner)
at System.Reflecti on.RuntimeMetho dInfo.Invoke(Ob ject obj,
BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo
culture, Boolean skipVisibilityC hecks)
at System.Delegate .DynamicInvokeI mpl(Object[] args)
at
System.Windows. Forms.Control.I nvokeMarshaledC allbackDo(Threa dMethodEntry
tme)
at System.Windows. Forms.Control.I nvokeMarshaledC allbackHelper(O bject
obj)
at System.Threadin g.ExecutionCont ext.runTryCode( Object userData)
at
System.Runtime. CompilerService s.RuntimeHelper s.ExecuteCodeWi thGuaranteedCle anup(TryCode
code, CleanupCode backoutCode, Object userData)
at System.Threadin g.ExecutionCont ext.RunInternal (ExecutionConte xt
executionContex t, ContextCallback callback, Object state)
at System.Threadin g.ExecutionCont ext.Run(Executi onContext
executionContex t, ContextCallback callback, Object state)
at
System.Windows. Forms.Control.I nvokeMarshaledC allback(ThreadM ethodEntry tme)
at System.Windows. Forms.Control.I nvokeMarshaledC allbacks()
at System.Windows. Forms.Control.W ndProc(Message& m)
at
System.Windows. Forms.Control.C ontrolNativeWin dow.OnMessage(M essage& m)
at System.Windows. Forms.Control.C ontrolNativeWin dow.WndProc(Mes sage&
m)
at System.Windows. Forms.NativeWin dow.DebuggableC allback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows. Forms.UnsafeNat iveMethods.Disp atchMessageW(MS G&
msg)
at
System.Windows. Forms.Applicati on.ComponentMan ager.System.Win dows.Forms.Unsa feNativeMethods .IMsoComponentM anager.FPushMes sageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData)
at
System.Windows. Forms.Applicati on.ThreadContex t.RunMessageLoo pInner(Int32
reason, ApplicationCont ext context)
at
System.Windows. Forms.Applicati on.ThreadContex t.RunMessageLoo p(Int32 reason,
ApplicationCont ext context)
at System.Windows. Forms.Applicati on.Run(Form mainForm)
at BackgroundWorke rDemo.Program.M ain() in C:\Documents and
Settings\David Veeneman\My Documents\Visua l Studio
2005\Demos\Back groundWorkerDem o\Program.cs:li ne 17
at System.AppDomai n.nExecuteAssem bly(Assembly assembly, String[]
args)
at System.AppDomai n.ExecuteAssemb ly(String assemblyFile, Evidence
assemblySecurit y, String[] args)
at Microsoft.Visua lStudio.Hosting Process.HostPro c.RunUsersAssem bly()
at System.Threadin g.ThreadHelper. ThreadStart_Con text(Object state)
at System.Threadin g.ExecutionCont ext.Run(Executi onContext
executionContex t, ContextCallback callback, Object state)
at System.Threadin g.ThreadHelper. ThreadStart()

Any ideas as to what's going on here? Thanks.

--
David Veeneman
Foresight Systems

Aug 2 '06 #1
1 6722
I found my answer. In the DoWorkEventArgs , e.Result can't be set if e.Cancel
is set to true. In my worker method, I was setting e.Cancel to true, then
setting e.Cancel to my unmodified source list, as an easy way of providing a
rollback in a cancellation.

The error doesn't show up until .NET creates the RunWorkerComple tedEventArgs
for the RunWorkerComple ted event. When it tries to set the e.Result
property, an InvalidOperatio nException will be thrown, with the error
message "Operation has been cancelled". If you then try to read e.Result in
the RunWorkerComple ted event handler, the app blows up. The moral of the
story is to check for cancellation before reading e.Result in a
RunWorkerComple ted event handler.

--
David Veeneman
Foresight Systems
Aug 2 '06 #2

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

Similar topics

2
4031
by: Lenin Torres | last post by:
Hi everybody I have an Union Query that works fine. I used this query as the RecordSource for a Form. That Form is used as a subform in another form. Everything works fine, except for the "Filter by form" feature. When the user tries to use Filter by form a messagebox is displayed: "There are too many controls in this form to perform a filter by form", after that,when the user exit the Filter by Form mode, Access crash, displaying a...
2
1565
by: ghost | last post by:
As the Subject indicates I have written a web page that makes use of several web service calls. Some of the web service calls are very fast so they called synchronously. Some web service calls are longer running so I call them asynch so that they can all run concurrently. The user base for the application that I am creating demands the partial response of the faster calls and a gradual update of their web page info from the balance of...
2
1098
by: Techno_Dex | last post by:
What is the correct way to debug a WS which makes it's call Asynch?
1
2641
by: Sean | last post by:
I am looking at using delegates to perform an asynchronous call. There will be a callback invoked at the end of the call. The client thread will wait on the WaitHandle from IAsyncResult (which is really a AsyncResult). My question is, when exactly is this WaitHandle signalled - is it: -when the asynchronous call finishes OR -when EndInvoke() is called (by the callback)
4
1877
by: EM_J | last post by:
I am implementing this interface in one of my pages. The RaiseCallbackEvent method runs a task for about 3 seconds. I've noticed when I am on that page and click a tab to navigate to another page, it may take up to 3 seconds to redirect. If I decrease the time to 500 ms, the redirect happens much faster. So it seems like this asynch task is not really asynch, since the redirect is waiting for it to complete. Am I misunderstanding...
0
1033
by: simonZ | last post by:
I'm using Asynch data tasks to create my data readers and after a couple of executions, the page doesn't render any more. There is always timeoutAsynchOperation. First time when this happens, in background, all the jobe in sql is done only the data is not thrown back. I guess: when user disconects from the pool, the asynch operation executes the procedure on sql server and when it is finished, it can't connect the user back to the pool....
0
1372
by: Patino | last post by:
I have a particular WS consumer application (Windows app) that was not able to read an error from the WS app because it was calling a method asynch. The client app just hangs there. But once I switched the call to a synch, the client app got the error message and displayed it nicely to the user. In this client app. the user does not have to do anything while waiting for results to come back from the web, so it makes sense to call the...
0
1397
by: jade9032 | last post by:
Hi, I am using the standard twain calling functions from twain.org and everything works correctly. The error happens when I try to press the cancel button on the scanner to cancel the print job. My program crashes and the error points to wiadss.dll. The problem will only occurs when I try to scan using WIA. For normal Twain interface, the cancelling works fine. The part of the code that crash is at DG_IMAGE,DAT_IMAGENATIVEXFER,MSG_GET.
5
11722
by: =?Utf-8?B?RWl0YW4=?= | last post by:
Hello, I need to create a background thread and two (or more) options are available to me: 1. BackgroundWorker 2. Asynch delegate method and BeginInvoke What are the differences between them in performance, complexity etc.
0
9416
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
10199
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
10032
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...
0
9849
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...
1
7393
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
6661
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
5293
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
5433
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3948
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

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.