I have a transaction that includes 12 queries for getting an export from the database and in this situation, I decided to do this with Task.WhenAll() and based on this decision and the ExceptionHandlerMiddleware that I wrote can only catch the first exception, not all of them. what solutions can I have in this case? thanks.
I found these two solutions but I'm worried about concurrency issues and I don't know how to fix this.
https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library
https://thesharperdev.com/csharps-whenall-and-exception-handling/
The way I would handle this is not allow exceptions within the task in the first place. You can accomplish this by having each task catch any unhandled exceptions and then store the text in an Error property. After tasks have completed you can inspect their Error property in the main thread and any with Error.Length != 0 can be printed out.
Here is an example of Gigantor's FileMapJoin class behaving as described above. I hope this helps.
Related
I am continuously struggling with this exception
An unhandled exception of type 'System.Windows.Forms.AxHost.InvalidActiveXStateException' occurred in AxInterop.SBXPCLib.dll
any help please, am i missing some thing.
Try this,it will solve your problem:
For each and every active x control, it is needed to create it first, so that all the events and handles should be initialized.
So try this:
axMDocView1.CreateControl()
The answer by Vishal is Fulfill your requirement but here I wanted to add one more thing with it. If you wanted to reflected this changes via all the threads and not only by calling thread (in multiple thread scenario) then use
axMDocView1.CreateControl();
axMDocView1.SkinAllThreads();
Actually in multiple threading scenario if your skinning code is in one of the thread then may be it is not reflect change for other current thread so at that time this code is play important role in it.
As far as I know, it's not good practice to use them when there's application specific error handling available.
I'm calling a method from a WCF service like so:
Service.Login += new EventHandler<LoginCompletedEventArgs>(LoginCompleted);
Service.LoginAsync(username, password);
In the resulting 'LoginCompleted' method I can use the following to check for errors:
if (e.Error == null)
As errors can be analysed once the method has completed, is it still necessary to place try-catch blocks around the 'LoginAsync' call? In other words, can anything go wrong with the 'LoginAsync' call?
Yes. Things can go wrong with the call itself... for example, say your network goes down and you can't actually complete the call. The try/catch would be useful for those situations. Handling the exceptions that occurred during the asynchronous operation is being done exactly how you should be doing it.
Basically, if you want to handle any exceptions in making the call, use the try/catch. If you want to handle any exceptions during the asynchronous operation, use the e.Error as you have been.
Not quite sure what could happen, but some scenarios jump to my head: out threads in the pool, out of memory...I would think that it is not necessary.
Correct me if I am wrong, but I noticed that the thread selected from the pool via ThreadPool.QueueUserWorkItem(GoneFishing)apparently "swallows" any exception that occurs within that thread.
This caused us a lot of trouble as we have designed an ordered thread chain, so if a thread does not finish well all the following chain is scrambled.
What is the most convenient way to deal with this in a proper fashion ?
If you consider using .NET 4.0, any exceptions thrown by a Task are automatically propagated to the parent thread when the Task is joined. Have a look here: http://msdn.microsoft.com/en-us/library/dd997415.aspx
For other related solutions check this question: Safe to throw an exception created on another thread C#
MSDN on migrating legacy multithreaded applications (from this page on exception handling in threads):
In general, the change will expose previously unrecognized programming problems so that they can be fixed. In some cases, however, programmers might have taken advantage of the runtime backstop, for example to terminate threads. Depending on the situation, they should consider one of the following migration strategies:
Restructure the code so the thread exits gracefully when a signal is received.
Use the Thread.Abort method to abort the thread.
If a thread must to be stopped so that process termination can proceed, make the thread a background thread so that it is automatically terminated on process exit.
In all cases, the strategy should follow the design guidelines for exceptions. See Design Guidelines for Exceptions.
This suggests that using Thread.Abort is an appropriate way to terminate a thread. Has something changed while I wasn't looking? The last I'd heard was this could cause unexpected behaviours so shouldn't be used.
Thread.Abort is a lot safer than it used to be for the following reasons.
The runtime will defer aborts while execution is in unmanaged code.
The abort will allow finally blocks to execute.
However, there is still a problem with exactly when the ThreadAbortException gets injected. Consider this code.
public class Example
{
private DateTime value = DateTime.MinValue;
public void DoSomething()
{
try
{
value = DateTime.UtcNow;
}
finally
{
}
}
}
If this code were running on a 32-bit platform the value variable could be corrupted if Thread.Abort was called and the ThreadAbortException were injected in the middle of the write to value. Since DateTime is 8 bytes the write has to take place using more than one instruction.
It is possible to guard against this by placing critical code in a finally block and by using Constrained Execution Regions, but it would be incredibly difficult to get right for all but the simplest types your define. And even then you cannot just put everything in a finally block.
Generally speaking, Thread.Abort will kill threads, leaving the data they were processing at the time in an unknown state. The state being unknown, it's usually not safe to deal with that data anymore. However, when you're trying to terminate a process, you are not expecting to deal with that thread's data anymore, so why not abort it?
Well, the problem with Thread.Abort() is that will abort the thread possibly in the middle of work. That might cause your state to be corrupted. That's why is advisable to use a volatile bool flag to control the thread, and let the thread finish its task gracefully, but based on that flag.
For more details, I recall this blog post.
I have a program that will analyzes source code. It can recursively go through a directory to find all projects, and then recursively go through the project to find all source code.
I want to create a cancel process button, which allows the user to stop the code parsing. I run the code parsing in a background worker. I want to be able to watch for the cancel event.
The problem is figuring out how to edit my code so that it will go and check that item and return back to the GUI. The parsing process goes several methods deep.
In a much smaller process, I successfully use a thread-safe singleton that has a bool that says whether or not a cancel has been requested, and stop the loop where it is running.
What would be the best way of working this cancel request into my code?
EDIT: Here is an idea, inspired by John Saunders' answer.
What if I run a background thread in my processing thread that watches for the Cancel Singleton to change, and then throw an exception from that process? Does this seem like good practice? This does not work as intended
EDIT 2: John Saunders' answer seems to be the best for now. I will just throw my own exception when the Singleton is true for now. I'll wait to see if any other solutions are proposed
Thread.Abort is a bad idea, as it interrupts the thread at an arbitrary point - probably interrupts it where you'd least like to be interrupted.
Set a flag that it seen by the thread being cancelled. Check it at the beginning of each operation. The idea would be to identify places in the code where it is safe to stop, and to check the flag at only those points.
You may find it useful to throw an exception at those points. The exception should be one that is not caught by your code until it reaches the boundary between your code and the UI. At that point, your code would simply return.
You could use the Thread.Abort() function on your background worker thread. This throws a ThreadAbortException which you can catch in any of your methods but which will atomatically be rethrown at the end of the catch blocks.
Also all finally-blocks will be executed.
It sounds like you're using the .NET backgroundworker class. I think you can pass a object parameter into the RunWorkerAsync method which then becomes accessible to the background thread in the DoWork event handler argument.
You could then modify that object in the UI thread (for example update a boolean cancel property) and periodically check on it from your background process.
There are various ways to perform a cancel on threaded operations; all of which involve the periodic checking of a flag or other value to determine if the thread should continue operating or not.
I would not recommend throwing exceptions for this feature. First of all, cancelling is not an exceptional circumstance, and second, it's overkill for what you're trying to implement.
Instead, you could use a simple, thread-safe boolean flag as a static member of a class accessible from any thread, or use a synchronization object such as a named Mutex. Signalling the synchronization object would then allow the thread to know it must cancel.