Home » C# Programming

Background Worker not firing RunWorkerCompleted event? Could be related to cross domain web service

Hey all,

I have a background worker object that doesn't seem to be firing its RunWorkerCompleted event.  The event handlers are properly wired up during the intialization of the class:

backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.ProgressChanged += OnBackgroundWorkerProgressChanged;
backgroundWorker.RunWorkerCompleted += OnBackgroundWorkerRunWorkerCompleted;

backgroundWorker.DoWork += BackgroundWorkFunction;

In the debugger, I can step through the BackgroundWorkFunction and watch the function correctly execute and return.  I have a breakpoint in my OnBackgroundWorkerRunWorkerCompleted event handler, but it never gets hit after the BackgroundWorkFunction returns.

There are some important details to know.  I have other tools which work just fine using this same code.  What is different about this particular project is that this code is being executed remotely by an IIS web service.  The code is executed by a local [TestMethod] in one domain, which calls a web service hosted on a different domain, which then executes this code for me.

I've made simple toy applications which use a web service to create a background worker and it seems to work fine (although I wasn't testing cross domain, just with localhost).  I've tried completely rebuilding the project (new solution, new web service) to see if something just got screwed up in Visual C#, but I'm hitting hte same problem still. 

I can't find any similar issues searching the internet, so I'm pretty stumped at what could be wrong, or even how to begin debugging :(.

Any help is greatly appreciated.  Thanks! :)


20 Answers Found


Answer 1

Out of curiosity, is your ProgressChanged handler getting called?

Answer 2

How odd!

This particular BackgroundWorkFunction doesn't call UpdateProgress (later uses of this object do, however).  I added an arbitrary UpdateProgress call to the BackgroundWorkFunction that it is currently failing on and re-ran the app to see if it would hit the ProgressChanged handler.

To my surprise, it did.  To my greater surprise, it then hit the work completed event handler for the first time in weeks.  I'm not sure what happened, but somehow that change seems to have kicked the app in its head and got things working properly.  I'm going to play around with it a bit.  I'll try removing that UpdateProgress call and see if it reverts to its old behavior, or what.

I'll post up if I figure out what may have happened.


Answer 3

Well, the update is frustraing, to say the least.

The code was executing perfectly, but then failed due to a server-side timeout.  I corrected the timeout and then tried removing the the UpdateProgress call I had inserted in the BackgroundWorkFunction. 

The behavior reverted.  The OnBackgroundWorkerRunWorkerCompleted event handler is never hit and the program hangs.  I tried putting the UpdateProgress call BACK to see if I could get it to start hitting the event handlers again, but now it doesn't hit either the ProgressChanged or RunWorkerCompleted event handlers.

The intermittent behavior I've seen today has me stumped.  Could there be something about the web service that is causing all the events to lose their wiring?  I've checked to make sure fresh dll's are getting deployed every time I change the code and run, so it doesn't seem to be an issue of something not getting updated.

Answer 4

You need to add some error catching code to your DoWork event.  Any error will cause the symptoms you describe.

Answer 5

I've stepped through the DoWork handler with a remote debugger and watched it complete and return successfully.  Could the problem you are describing be a result of a lower level error which is handled by lower level code and never reported to me?

I'm imaging a case where there is a low level error which we ignore at some point deeper in the code which doesn't affect normal execution, but causes problems when executed by the web service.  Is that what you're thinking might be the problem?


Answer 6

Masking errors will do it.  If you have any empty Catch blocks, get rid of them.

Answer 7

Sounds like a probable candidate.  I'll start digging and let you guys know.  Thanks a ton!

Answer 8

I found a purposeful ArgumentException that the code throws, and then just catches and continues.  Was hoping to find something more low level.  I'll look a bit more in depth and see if I can't find anything else.  If not, I'll modify the library to not throw that ArgumentException and see if it makes a difference.

Answer 9

Alright.  I've run through a few times, and can't find any lower level exceptions that are being masked.  In the exception settings for the debugger I have it set to break on all exceptions, or at least, all exceptions in the default list:

C++ Exceptions
CLR Exceptions
Managed Debugging Assistants
Native Run-Time Checks
Win32 Exceptions

Perhaps there are more I can add to this list and monitor?

I removed the argument exception that the code was generating and have run through the whole routine several times without any detected errors and still seem to be losing my event handler wiring.

Is there a way in the debugger to monitor who is subscribed to an event so I can try to find at what point I'm losing my wiring?

Answer 10

Post  the code containing the RunWorkerAsync statement.  (Just a hunch)

Answer 11

I basically call a function RunBackgroundWorker(BackgroundWorkFunction) which appears below:

private void ExecuteBackgroundWorker(DoWorkEventHandler doWorkHandler)  
    _backgroundWorker.DoWork += doWorkHandler;  

_backgroundWorker is a member for the class:

private readonly BackgroundWorker _backgroundWorker = new BackgroundWorker();  

The variable is then initialized in the constructor:

public Class(/* unrelated arguments */)  
    // Initialize BackgroundWorker.  
_backgroundWorker.WorkerReportsProgress = true;  
    _backgroundWorker.ProgressChanged += OnBackgroundWorkerProgressChanged;  
    _backgroundWorker.RunWorkerCompleted += OnBackgroundWorkerRunWorkerCompleted;  

Answer 12

Well, you're definitely on track for the location of the issue.  I'm doing some ghetto printf style debugging using the ReportProgress function and the ProgressChanged event handler.  My modified RunBackgroundWorker function from the last post:

private void RunBackgroundWorker(DoWorkEventHandler doWorkHandler)  
    // Test  
    _backgroundWorker.DoWork += doWorkHandler;  
    // Test  
    // Test  

I hit the breakpoint in the ProgressChanged event for the first two ReportProgress calls, but not the last.  Basically, any ReportProgress call stops hitting the ProgressChanged event handler after the RunWorkerAsync() is called.

I'm going to look into why that might be.  Anyone have any ideas/tips?

Answer 13

I don't understand the code you posted.  Post the code that calls that code.

Answer 14

/// This is the web service function that I am remotely
/// calling.
publicbool RemoteDataValidate()  
/// Some configuration stuff excluded
    dataValidator = new DataValidator(databaseConnection);  
/// Check to see if validation succeeded and return result

/// The ValidateAsync function inside my dataValidator function
publicvoid ValidateAsync()  
/// Some Logging stuff excluded

Answer 15

There it is:  eventWaitHandle.Wait(-1);

You have to let that funcition complete.  Remove that statement.  If you want to wait, use a timer.

Answer 16

Sorry, I probably should have clarified that I am signaling my eventWaitHandle in my OnBackgroundWorkerRunWorkerCompleted function.  The problem is that the event handler never gets executed, so I never signal and allow my web service call to complete.

I'm still trying to figure out why my event handlers seem to not get executed once I make the call to RunWorkerAsync().


Answer 17

Still working on the issue.  I'll post when I find the solution. 

I've managed to extract the web service from the equation and can reproduce the problem when running the code locally.  I wonder if it has anything to do with running the code through the visual studio test framework.  I'll be playing around with that next.

Answer 18

one thing to be very careful of:  the main purpose of the background worker control is to ensure that (RunWorkerCompleted, ReportProgress &c) notifications are getting called on a main application thread, or GUI thread.  If you are invoking a background worker control from a non-gui thread, then you are much more likely to run into problems.  So, I would say, use backgroundworker only in windows forms programming and then only from the gui thread.  In all other scenarios do your own threading.

Answer 19

Thanks for the tip JoGo.  I'll have to keep that in mind for future coding.  Sadly, the backgroundworker is in the API that I'm using, so it's not code I can easily change.

I finally found a solution for this though.  The API that I'm using has windows forms code in it and as a result my project needs a reference to the windows forms libraries.

I added the following line to my code before I invoke the portion of the API which creates the background worker:


and now the events seem to be getting generated/handled correctly.  I'm not sure of the in depth details on what this line changes exactly, but I'm assuming that if I created a new windows forms project, this line might appear somewhere in the autogenerated code.  Since this isn't a windows forms application though, I guess I needed to add it myself. 

Perhaps someone can add a better explanation, but for now, in case anyone else hits this problem, here is the solution :).

Answer 20

I had the same problem and found the solution to be setting a result value:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
 e.Result = <any non-null value>;

If you do set e.Result, OnBackgroundWorkerRunWorkerCompleted is called.

If you don't care abut the return value, just set e.Result = true.

If you don't set e.Result, OnBackgroundWorkerRunWorkerCompleted is not called.


I am trying to call a cross domain ASMX webservice hosted on my web server from my silverlight application in my development box.

I have copied following clientaccesspolicy.xml to root of my web server

<?xml version="1.0" encoding="utf-8"?>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
        <resource path="/" include-subpaths="true"/>

By tracking under Fiddler, I can see that my SL app call the clientaccesspolicy.xml file and gets it without any problems, but after that it doesn't call the actual URL.and instead i am getting follwoing runtime error :

"An error occurred while trying to make a request to URI 'http://www.mywebsite.com/webser/emailsender.asmx'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. Please see the inner exception for more details."

I tried even putting crossdomain.xml file but no resuts.

Can any body tell me where i am going wrong?

Thanks in advance,
Pinal Bhatt



I have made a form in InfoPath 2010 which queries for exchange rates. It has 3 text boxes as follows:

base-currency to-currency Exchange-Rate

The first two text boxes takes value from the user and queries the web service (not on my SharePoint 2010 domain) and gets the result in the Exchange-Rate text box.

This form works fine when i preview in InfoPath 2010, but when i publish it to the SharePoint 2010 site, i got a cross-domain error. So i googled and found out that i have to create a data connection file for querying the data. I created it and republished my form. I have also enabled the Allow cross-domain data access for user form templates that use connection settings in a data connection file from the Configure InfoPath Forms Services in the Central Administration.

Now when i open the form in Internet Explorer, i get the error An error occurred while trying to connect to a Web service .

Can someone help me with this.




I have my SharePoint site on port 80 and I have just configured an administrator approved form template and I am using it on that site. It is posting to a webservice on port 8080 on the same site, but whenever I click to submit the form I get this error: "An error occurred while trying to connect to a Web service.", however the web service is up and operational and I even associated the method I need to use on submit in InfoPath. When I check the application security log I see this error many times:

"An exception occurred when trying to issue security token: There was no endpoint listening at http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc/actas that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.."

Any ideas?




ATL generates a class that inherits from IConnectionPointImpl to fire events.  That class uses CComDynamicUnkArray by default.

However, in some instances it is necessary to fire events from worker threads that reside in different apartments, and the ATL code by itself is not enough.  Mutliple solutions are out there that either replace IConnectionPointImpl, CComDynamicUnkArray, or both (e.g., http://support.microsoft.com/kb/280512). 

Suppose that the class is an out-of-process server.  The main thread is in the MTA.  The worker threads also have been initialized to start in the MTA.  Since the interface to the sink object is advised on a thread residing in the MTA, and fired from another thread residing in the MTA, is it necessary to modify the ATL generated code?  In other words, are the solutions above trying to address the problem of having an interface pointer used in multiple apartments -- and hence the need to marshal the interfaces through the use of a Global Interface Table?  If so, then no modification should be necessary if if all the threads reside in the same apartment (MTA), right?





I have created a workflow service (xamlx) and hosted it on IIS. The web.config file of the service is:

<?xmlversion="1.0"encoding="utf-8"?><configuration><system.web><compilationdebug="true"targetFramework="4.0"/></system.web><system.serviceModel><services><servicename="VacationRequestService"><endpointcontract="IVacationEntry"binding="wsHttpBinding"/></service></services><behaviors><serviceBehaviors><behavior><!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --><serviceMetadatahttpGetEnabled="true"/><!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --><serviceDebugincludeExceptionDetailInFaults="false"/></behavior></serviceBehaviors></behaviors><serviceHostingEnvironmentmultipleSiteBindingsEnabled="true"aspNetCompatibilityEnabled="true"/></system.serviceModel><system.webServer><modulesrunAllManagedModulesForAllRequests="true"/></system.webServer></configuration>

I have added 2 xml files for allowing cross domain access:



and crossdomain.xml

<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">

All these files are accessible from the localhost urls i.e. http://localhost:8000/VRequest.xamlx, http://localhost:8000/clientaccesspolicy.xml and http://localhost:8000/crossdomain.xml.


Next, I created a Silverlight application and added the service located at http://localhost:8000/VRequest.xamlx as reference. The first problem that I saw was that my ServiceReferences.ClientConfig didnt get generated properly. But I copied the config entries from my other projects and it looked similar to this:




But when I tried to run my silverlight application, it throws the cross-domain exception. The exact message that I get is:

An error occurred while trying to make a request to URI 'http://localhost/ProWF/VacationRequestService.xamlx'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.


And when I checked the inner exception, it said:


System.Security.SecurityException: Security error.
  at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
  at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
  at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)


So, I wanted to know if someone has tried the same scenario i.e. accessing a workflow service hosted in IIS inside silverlight?

What am I doing wrong? Am I missing anything?







I get this error when trying to access a self hosted wcf service...

An error occurred while trying to make a request to URI 'http://localhost:2363/Service1.svc'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.

Can someone please explain what I need to do to get this to work, I do not have any cross domain policy file. And don't know how that is supposed to look like.


Hi All ,

I have designed my silverlight application with silverlight enabled wcf service , it works fine locally and i am able to view the data but when i deploy the application in the IIS , i face cross domain policy errors .

I have also added the clientaccesspolicy.xml & crossdomain.xml in the D:\Inetpub\wwwroot path . 

Not sure whats the problem . Please Help .

Below is the details of the error message :

System.ServiceModel.CommunicationException was unhandled by user code
  Message=An error occurred while trying to make a request to URI 'http://MyServer/MyApplication/MyService.svc'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.
       at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
       at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
       at DMT.MyServiceReference.MyServiceClient.MyServiceClientChannel.EndGetApplications(IAsyncResult result)
       at DMT.MyServiceReference.MyServiceClient.DMT.MyServiceReference.MyService.EndGetApplications(IAsyncResult result)
       at DMT.MyServiceReference.MyServiceClient.OnEndGetApplications(IAsyncResult result)
       at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)
  InnerException: System.Security.SecurityException
            at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
            at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
            at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
       InnerException: System.Security.SecurityException
            Message=Security error.
                 at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
                 at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
                 at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)


Hi All,

I have confusion here,  I need to build SL client which will access HTTPS service which is in same local network as of SL web server but on different server.

As per source: http://forums.silverlight.net/forums/t/12741.aspx such access is restricted in Cross-zone, while it is allowed in cross domain.

I am not sure what zone/domain my application falls in. I tried hosting HTTPS service on one machine and SL app on another machine, however it didnt work, but it worked when I hosted both app and service on same web server. I suspect my crossdomain xml configuration could have gone wrong, hence the issue.

Could you please let me know if hosting HTTPS service on one machine and SL4 app accessing service hosted on different machine in same local network works?




Hi there,

I'm getting the well known error:

An error occurred while trying to make a request to URI  This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.

I have tried all things I've found on the web, including using generic lists (instead of observable ones), basicHttpBinding, adding a clientaccesspolicy.xml/crossdomain.xml and so on, but I'm still getting the same error.

This is my scenario:

I have a Silverligth 4 Web Project, which is hosted in second web project . The second web project also contains the WCF web services (FW 3.5) and other ASPX's. I'm using Windows 7 x64 and the development server (not the IIS).

BTW: I have already checked posts like this :http://blogs.msdn.com/b/carlosfigueira/archive/2008/03/07/enabling-cross-domain-calls-for-silverlight-apps-on-self-hosted-web-services.aspx

Thanks a lot


problem consuming WCF service in silverlight 4 application:


throw new Error("Unhandled Error in Silverlight Application An exception occurred during the operation, making the result invalid.  Check InnerException for exception details.   at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()\n   at SLClient.ServiceReferenceWcfSLServicemt.CreateCompletedEventArgs.get_Result()\n   at SLClient.MainPage.wcfClient_CreateCompleted(Object sender, CreateCompletedEventArgs e)\n   at SLClient.ServiceReferenceWcfSL.WcfSLServiceClient.OnCreateCompleted(Object state)");

I have clientaccesspolicy.xml and crossdomain.xml inside the solution folder.




In the following document it states that the names have to be the same for both user and service accounts when moving a TFS server from one environment to another.  In our case it is from one domain to another.  For Example, DomainA\jane.smith will now need to be DomainB\jane.smith.


We are able to have the service accounts named the same in the new domain but the user accounts will not be so lucky. Do we have to recreate all of the user accounts in the new domain or is there a way to map the SIDs from the old domain accounts to the new domain accounts without having to keep the account names the same?  For example, DomainA\jane.smith -> DomainB\jsmith.

Is there any way to map the SIDs using the TFSAdminUtil to UserIDs in the new domain with new names?  If not, what happens to all the history in TFS with the old domain IDs?  Do we just see SIDs or are you still able to see the users associated with the changes?

Thanks in Advance,




Starting from my understanding about Background worker control, I understands that the background worker runs the code in its "DoWork" method in a seperate thread, while ProgressChanged and RunWorkerCompleted events are executed on the main thread.

In my senerio, I report the progress and under an specail condition my application displays a message box to the user in "ProgressChanged" method using MessageBox.Show(). and in "RunWorkerCompleted" event the application finalize some work. There the sequence is important, suppose that the message is of Yes or No type and finalization depends on it. Now when i run my application, the background worker triggers "ProgressChanged", but as soon as backgroundWorker's cancelAsync() is called the program leaves the current "ProgressChanged" method and executes "RunWorkerCompleted" code first.

How can i make sure that the "RunWorkerCompleted" code executes only after the completion of ProgressChanged method.

Thanks and Regards,



An error occurred while trying to make a request to URI 'http://localhost:4846/Service1.svc'. This could be due to to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent.

Here is the VS08 Dev Environment giving some context to the location of the code where the exception was thrown;


 and the entire error is at the top of my blog under Silverlight DataGrid Theming.  http://greghazzard.blogspot.com/

None of the possible solutions that have worked for others have helped me thus far in solving this cross-domain issue. I am using Visual Studio 2008 Development Server and not IIS,  If for some reason my exercise with getting the new Dec 2008 Silverlighgt DataGrid and recommended workaround to get Silverlight SDK Themes to work with the DataGrid has introduced a 'wrinkle' into the mix, then I will gladly move to IIS if there is reason to. For obvious debugging reasons I hope to remain in VS08.

1. setting the binding to basicHttpBindingin the web.config.

   <endpoint address="http://localhost:4846/Service1.svc" binding="basicHttpBinding"    bindingConfiguration="BasicHttpBinding_Service1" contract="ServiceReference1.Service1"    name="BasicHttpBinding_Service1" />
   <service behaviorConfiguration="XTO_Silverlight_WCF_CurrentSummary.Web.Service1Behavior"    name="XTO_Silverlight_WCF_CurrentSummary.Web.Service1">
    <endpoint address="" binding="basicHttpBinding" contract="XTO_Silverlight_WCF_CurrentSummary.Web.Service1" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

 2.  My app began without either clientaccesspolicy.xml or crossdomain.xml. Do I now require one? Here is a discussion about deleting one of them should I have had that problem. Without either one present, that is clearly not causing my current error exception.         http://silverlight.net/forums/t/61381.aspx

3. selecting a specific port address (3012 in my case) under Web properties in the Project settings.


                <binding name="BasicHttpBinding_Service1" maxBufferSize="2147483647"                    maxReceivedMessageSize="2147483647">
                    <security mode="None" />
            <endpoint address="http://localhost:4846/Service1.svc" binding="basicHttpBinding"                bindingConfiguration="BasicHttpBinding_Service1" contract="ServiceReference1.Service1"                name="BasicHttpBinding_Service1" />

 any other ideas anyone? 

With appreciation,

Greg Hazzard




I'm using a BackgroundWorker to perform some file deletions. The main UI for the application is a 'windows explorer' style interface, so I'm showing a small 'Progress Dialog' in another form while the delete operation is running. The progress window includes a progress bar and a cancel button. The form implements an IProgressCallback interface which allows us access to certain methods (SetText, SetValue etc)

The progress window is shown to the user on the main UI thread

ProgressWindow progress = new ProgressWindow();
progress.CancelButtonClicked += new ProgressWindow.WorkCancelled(progress_UserCancelled);
progress.Begin(0, filesToDelete.Count);

// Starts the deletion process on the worker thread and displays the progress// of the operation
DeletionStartArguments arguments = 
	new DeletionStartArguments(filesToDelete, UserOptions.Current.NumberOfPasses, progress);

In the main DoWork method of the BackgroundWorker, there are a couple of situations we need to handle. The user could've selected to delete 10 files and wants to cancel the delete operation after a few files. Also, a delete operation may error due to whatever reason, we also want to handle this gracefully.

NB: This will mainly be running on Windows XP, so I don't have acces to Transactional NTFS. Additionaly, some of the files being deleted are likely to be large so don't want to take part in a trasactional API (e.g http://transactionalfilemgr.codeplex.com/). Therefore, if the delete process in DoWork has deleted 2 files out of 10 when you want to Cancel, we just want to exit DoWork and report on the files that were deleted before a cancel \ error.

If the Cancel button in the Progress form is clicked, it will raise an event to our main UI where we can call CancelAsync


privatevoid progress_UserCancelled()


Here is the main code in the DoWork method

My questions are around the e.Cancel and Exception handling I have put into place here. As you can see from the code, I'm basically overriding the default behaviour here by not setting e.Cancel and catching any exceptions that could be thrown by FileCleaner.Delete

This is so the routine will exit and return a DeletionCompletedArguments object.



privatevoid deletionWorker_DoWork(object sender, DoWorkEventArgs e)
	DeletionStartArguments arguments = (DeletionStartArguments)e.Argument;
	IProgressCallback progress = arguments.ProgressInformation;
	Exception deleteException = null;      
	int step = 0;
	List<string> deletedFiles = new List<string>();

	foreach (string file in arguments.FilesToDelete)
		// We won't set e.Cancel here because we still want to return a DeletionCompletedArguments// object to RunWorkerCompleted that contains information for any files that have been// deleted. If we set e.Cancel, the object wouldn't be available and would throw an exception// 'request has been cancelled'if (deletionWorker.CancellationPending)

		var displayText = string.Format(Resources.DeletingFile, Path.GetFileName(file));
		DeletionState state = new DeletionState(displayText, progress);
		deletionWorker.ReportProgress(step, state);

			if (FileCleaner.Delete(file, arguments.NumberOfPasses))

		catch (Exception ex)
			// Catch all exceptions, store in our 'deletionException' object and exit// the loop. This is then returned in the DeletionCompletedArguments
			deleteException = ex;

	DeletionCompletedArguments completedArguments
		= new DeletionCompletedArguments(deletedFiles, progress, deleteException);
	e.Result = completedArguments;


The WorkerCompleted code looks like the following

privatevoid deletionWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
	DeletionCompletedArguments completed = (DeletionCompletedArguments)e.Result;

	// If error has occurred, report and returnif (completed.Error != null)

	// Inform user cancellation has taken placeif (completed.ProgressInformation.UserCancelled)

	 * Even if the deletion was cancelled or an error occurred deleting a particular
	 * file, we may have deleted a number of files prior to the cancel \ error
	 * We still need to update the UI to remove the files that were deleted successfully
	 * and remove the progress form that is still displayed at this point

		// Tidy up views, refresh by removing any files we've successfully deletedforeach (string deleted in completed.DeletedFiles)


In the above, I can tell if the user chose to cancel from a property in the IProgressCallback interface. I've wrapped the Exception in the DeletionCompletedArguments object, which we can test to see if an Exception occurred in DoWork.

I can also access the IProgressCallback interface of the ProgressForm to end the ShowDialog(), the progress form is still visible at this point & we always want to hide it after the operation has completed - regardless of outcome.

Therefore, if either of the two scenarios we are trying to handle occur, we can still proceed to access the completed.DeletedFiles list and process the UI.

If we didn't do this, trying to access the Result object would result in either a TargetInvocationException in the case of an error, or an InvalidOperationException in the case of a cancellation.

The above is working perfectly , just a bit concerned that I'm kludging the behaviour here!


Q: Are there any other recommended ways to access the Result object after a cancellation or exception? Or is the above an acceptable way of handling?




I'm getting

"{System.ServiceModel.CommunicationException: An error occurred while trying to make a request to URI This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. "

error when my Silverlight application in Web Role tries to access a WCF service hosted in a Worker Role. I attached crossdomain.xml and clientaccesspolicy.xml files to my worker role project which contains WCF service. But still Silverlight client is failing with above error (note that same WCF service can be accessed from a windows console client without any error). Web development helper tool always shows 404 error for both crossdomain.xml and clientaccesspolicy.xml files when client tries to access. 

Is there any special way to attach cross domain and client access policy files to worker role projects ? Where does Azure keep these files at the runtime ? Looks like Azure doesn't deploy my XML files to ROOT (not sure where this folder is) of WCF service running in Worker role. Note that I'm using Windows Azure SDK 1.2.

Thanks and regards




I'm writing a DLL which will be used by a new application, in which some of the processing needs to be done in a background thread (web calls).

During the processing of this background thread, it's highly likely that the main application will need to enable, disable, and possibly update parts of its UI, however when attaching an "enable / disable" function to the "work begun" and "work completed" events I've created, I'm coming across the error "Cross-thread operation not valid".

I've seen the MSDN document on the error, and followed a couple of links on Google, however all the details I've seen only seem to refer to different threads within the same assembly and require knowledge of the calling object (many references to e.g. "this.buttonX").

How can I allow the application front end code to be called safely without prior knowledge of what it will contain?  I know I can switch off the error by setting CheckForIllegalCrossThreadCalls to false, but I get the impression that that's a less than ideal solution.

For reference, the MSDN document states


delegate void SetTextCallback(string text);

private void setTextSafeBtn_Click(object sender, EventArgs e)
  this.demoThread = new Thread(new ThreadStart(this.ThreadProcSafe));

private void ThreadProcSafe()
  this.SetText("This text was set safely.");

private void SetText(string text)
  if (this.textBox1.InvokeRequired)
    SetTextCallback d = new SetTextCallback(SetText);
    this.Invoke(d, new object[] { text });
    this.textBox1.Text = text;

I'm working on VS 2005 add-in that needs to capture details as files are added to, removed from, or deleted from Web projects.  This is the basic code I'm using to wire up the events... _applicationObject = (DTE2)application;events = (EnvDTE80.Events2) _applicationObject.Events; projItemEvents = (ProjectItemsEvents) events.ProjectItemsEvents; // also tried events.SolutionItemsEvents and events.GetObject("CSharpProjectItemsEvents");projItemEvents.ItemAdded +=   new _dispProjectItemsEvents_ItemAddedEventHandler  (this.ItemAdded);projItemEvents.ItemRemoved +=  new _dispProjectItemsEvents_ItemRemovedEventHandler  (this.ItemRemoved);projItemEvents.ItemRenamed +=  new _dispProjectItemsEvents_ItemRenamedEventHandler  (this.ItemRenamed); This works great for all project types except Web projects - for all other project types, the events fire and I can get to the corresponding properties of the ProjectItems passed to the event handlers.  Unfortunately, these events don't seem to be firing when I perform the corresponding action(s) in Web projects.  I assume that this is an unfortunate side effect of the new VS2005 Web project model, which doesn't use .csproj or .vbproj files any more.  Has anyone else run into this problem or been able to find a viable workaround? Thanks for any help! Dan Kahler      

Hi All,

I am working on visual webpart of SharePoint 2010. I am using a <SharePoint:DateTimeControl> i m trying  to fire OnDateChanged event on it. I am not getting the Appropriate way to create the event. please help me out!!!!


Hi, i have problems with this WUC. I created two instances in a page. The first instance fired up imgMensaje_Click without a problem, but the second one event doesn't fired up at all.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="wucListaMensajes.ascx.cs" Inherits="controles_wucListaMensajes" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="act" %>

<asp:UpdatePanel ID="upListaMensajes" runat="server" UpdateMode="Conditional">
                                <asp:ImageButton ID="imgMsj" runat="server" ImageUrl='<%# Eval("imagen") %>' OnClick="imgMensaje_Click"/>
                        <asp:BoundField DataField="fecha" HeaderText="F. envio"/>
                        <asp:BoundField DataField="unidad" HeaderText="Unidad" />
                        <asp:BoundField DataField="sentido" HeaderText="Sentido" />
                        <asp:BoundField DataField="texto" HeaderText="Texto" />
                        <asp:BoundField DataField="idMensaje" Visible="false" />
                    <EmptyDataTemplate><p>No hay mensajes para la unidad seleccionada.</p></EmptyDataTemplate>
                    <SelectedRowStyle CssClass="fila_seleccionada"/>

Event's code:

    protected void imgMensaje_Click(object sender, EventArgs e)
        RaiseBubbleEvent(this, null);

WUC instance:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="wucMensajes.ascx.cs" Inherits="controles_wucMensajes" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="act" %>
<%@ Register TagPrefix="wuc" TagName="ListaMensajes" Src="~/controles/wucListaMensajes.ascx"%>

<asp:UpdatePanel ID="upMensajes" runat="server"  UpdateMode="Conditional">
        <asp:AsyncPostBackTrigger ControlID="cbMsjTodasUnidades" EventName="CheckedChanged"/>
            SelectedDate='<%# System.DateTime.Today %>'
             <div class="div_tab_panel">
                <div class="busqueda">
                        WatermarkText="Fecha a consultar"
                    <asp:CheckBox ID="cbMsjTodasUnidades" runat="server" Checked="false" Text="Ver todos" OnCheckedChanged="cargarMensajes_Evento" AutoPostBack="true" />
                    <asp:TextBox ID="tbFechaMensajes" CssClass="txt_calendario" runat="server"></asp:TextBox>
                    <asp:Button id="btnBuscarMensajes" CssClass="btn_busqueda" runat="server" Text="Buscar" OnClick="cargarMensajes_Evento"/>
                <wuc:ListaMensajes ID="wucListaMensajes" runat="server" Conversacion="false"></wuc:ListaMensajes>
            <div id="div_conversacion" style="display:none">
            <div class="conversacion">
                <wuc:ListaMensajes ID="wucConversacion" runat="server" Conversacion="true"></wuc:ListaMensajes>
                <asp:TextBox ID="tbMensaje" runat="server" TextMode="MultiLine"></asp:TextBox>
                <p class="info">Presione la tecla ESC o haga click en la X para cerrar esta ventana.</p>

Setting a breakpoint on RaiseBubbleEvent, when i click  firs't imagebutton event fires up, but when click second0s imagebutton nothings happen.

I'm working on a bug with an existing application that I did not originally create.  The client is a Win Forms app, and it communicates with an ASP.NET Web Application with an ASP.NET Service.  I'm currently converting some synchronous calls that lock up the GUI thread for too long into asynchronous calls.  The proxy class for the ASP.NET service already had the async methods.  Under normal circumstances, everything works as expected, but if an exception is thrown in the service method on the server, the exception bubbles up to my client app's AppDomain.CurrentDomain.UnhandledException handler, instead of returning execution immediately to the completed event I hooked up (which is what I was expecting).  Does anyone know why or what would cause the completed event handler not to be fired when an exception occurs on the server?  Could a web.config setting be missing from the service or something?  I tried creating a simple example, but it worked fine, so I definitely know there's something fishy going on.  I even commented out the entire web.config in my sample project, and it still worked, so I figure it has nothing to do with that.  Any ideas?

<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure