473,386 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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
BackgroundWorker 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 RunWorkerCompletedEventArgs.Cancelled property is wrong.

My worker method is called by the BackgroundWorker_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(WidgetList sourceList, BackgroundWorker
backgroundWorker, DoWorkEventArgs e)
{
// Create deep copy (by serialization)
WidgetList resultList = sourceList.DeepCopy();

// 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(100);

// Check cancellation
if (backgroundWorker.CancellationPending)
{
// Set DoWork event args
e.Cancel = false;

// Return unmodified list
return sourceList;
}

// Report progress
backgroundWorker.ReportProgress(i);
}

// Set return value
return resultList;
}

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

System.Reflection.TargetInvocationException was unhandled
Message="Exception has been thrown by the target of an invocation."
Source="mscorlib"
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(Objec t target,
Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes,
RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target,
Object[] arguments, Signature sig, MethodAttributes methodAttributes,
RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,
BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo
culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at
System.Windows.Forms.Control.InvokeMarshaledCallba ckDo(ThreadMethodEntry
tme)
at System.Windows.Forms.Control.InvokeMarshaledCallba ckHelper(Object
obj)
at System.Threading.ExecutionContext.runTryCode(Objec t userData)
at
System.Runtime.CompilerServices.RuntimeHelpers.Exe cuteCodeWithGuaranteedCleanup(TryCode
code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(Exec utionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionCon text
executionContext, ContextCallback callback, Object state)
at
System.Windows.Forms.Control.InvokeMarshaledCallba ck(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallba cks()
at System.Windows.Forms.Control.WndProc(Message& m)
at
System.Windows.Forms.Control.ControlNativeWindow.O nMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.W ndProc(Message&
m)
at System.Windows.Forms.NativeWindow.DebuggableCallba ck(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchM essageW(MSG&
msg)
at
System.Windows.Forms.Application.ComponentManager. System.Windows.Forms.UnsafeNativeMethods.IMsoCompo nentManager.FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData)
at
System.Windows.Forms.Application.ThreadContext.Run MessageLoopInner(Int32
reason, ApplicationContext context)
at
System.Windows.Forms.Application.ThreadContext.Run MessageLoop(Int32 reason,
ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at BackgroundWorkerDemo.Program.Main() in C:\Documents and
Settings\David Veeneman\My Documents\Visual Studio
2005\Demos\BackgroundWorkerDemo\Program.cs:line 17
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[]
args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence
assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context( Object state)
at System.Threading.ExecutionContext.Run(ExecutionCon text
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

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

--
David Veeneman
Foresight Systems

Aug 2 '06 #1
1 6692
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 RunWorkerCompletedEventArgs
for the RunWorkerCompleted event. When it tries to set the e.Result
property, an InvalidOperationException will be thrown, with the error
message "Operation has been cancelled". If you then try to read e.Result in
the RunWorkerCompleted event handler, the app blows up. The moral of the
story is to check for cancellation before reading e.Result in a
RunWorkerCompleted 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
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...
2
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...
2
by: Techno_Dex | last post by:
What is the correct way to debug a WS which makes it's call Asynch?
1
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...
4
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...
0
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...
0
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...
0
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...
5
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...

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.