I recently used multiple threads for development. I found Ahha and programming when I was looking for information. This article on the blog, I think it is a good idea, and I will repost it here.
Article name: Unified thread Exception Handling
Source: http://www.cnblogs.com/oujinliang/archive/2009/12/26/1633041.html
The original article is as follows:
-------------------------------------------------
Unified thread Exception Handling
In a Service program, there are usually multiple Worker threads which may run independently or in a ThreadPool. In order not to cause the main program to crash due to the unprocessed exceptions of the Worker thread, we need to handle all the Worker threads in a consistent way, such as notifying the main thread, then perform different processing based on different exceptions, and finally stop the problematic thread elegantly. For example, the following program:
static void Main(string[] args)
{
Thread thread1 = new Thread((ThreadStart)Worker_1);
thread1.Start();
Thread thread2 = new Thread((ThreadStart)Worker_2);
thread2.Start();
thread1.Join();
thread2.Join();
}
static void Worker_1()
{
try
{
// Do something here.
}
catch (Exception e)
{
// TODO, handler exception,
// Notify the main thread and stop this thread gracefully.
}
}
static void Worker_2()
{
try
{
// Do something here.
}
catch (Exception e)
{
// TODO, handler exception,
// Notify the main thread and stop this thread gracefully.
}
}
In this program, we have two working threads Worker_1 and Worker_2, which have the same exception handling process. However, the problem is that when there are many types of tasks, such as Worker_3 and Worker_4, all such thread functions must perform the same exception processing, leading to unnecessary repetition, and it is easy to forget. How can we remove such duplicates? The first thought of is a solution that provides an auxiliary function that accepts an Action as the parameter:
static void SafeThread(Action action)
{
try
{
action();
}
catch (Exception e)
{
// TODO, handler exception,
// Notify the main thread and stop this thread gracefully.
}
}
Then Worker_1 can write as follows:
static void Worker_1()
{
SafeThread(delegate
{
// Do something here.
});
}
This can simplify the process. However, this method may make the original Worker method have a strange packaging, and we still need to do the same processing for each Worker. Since the Thread constructor accepts a ThreadStart parameter, can we convert an original direct Worker method (also of the ThreadStart type) to a ThreadStart type that can handle exceptions? Yes. First, we define the conversion function as follows:
static ThreadStart SafeThread(ThreadStart threadStart)
{
return () =>
{
try
{
threadStart();
}
catch (Exception e)
{
// TODO, handler exception,
// Notify the main thread and stop this thread gracefully.
}
};
}
Then our Worker thread will be very direct:
static void Worker_1()
{
Console.WriteLine("Worker 1");
// Do something here.
}
static void Worker_2()
{
Console.WriteLine("Worker 2");
// Do something here.
}
The main program needs to be slightly changed, but it is also very simple:
static void Main(string[] args)
{
Thread thread1 = new Thread(SafeThread(Worker_1));
thread1.Start();
Thread thread2 = new Thread(SafeThread(Worker_2));
thread2.Start();
thread1.Join();
thread2.Join();
}
This reduces the burden on the thread function writers and does not omit a thread that is not processed. A simple search can solve the problem.
What should we do with the ParameterizedThreadStart and WaitCallback threads that accept a parameter?
2 0 (please comment on the article)
«Previous: The only valid measurement of code quality?
» Next article: make good use of the C #3.0 Extensions method-and common auxiliary method sets
Posted @ Ahha reading (1086) Comments (15) EDIT favorites
Comment reply reference
#58.24.84 on the first floor. * 2009-12-27 | asdfffff111 [unregistered users] lz is a strange way to return anonymous delegation.
Thread thread1 = new Thread (SafeThread (Worker_1 ));
If you do not read the definition of the SafeThread method, the write will undoubtedly be wrong, because a method without parameters should be put in the Thread constructor.
This method was invented by the landlord, and it is not very good.
Reply to reference
#218.240.33.*2009-12-27 | gxq [unregistered user]. sofa !!!
Taught.
View reply reference
#3 floor | since the lone sword is a thread, why not define a thread? Rewrite Start (); Wrap it and add a try... catch.
View reply reference
#4 floor [main poster] | Ahha @ Gu Jian
Thread is a sealed class and cannot be inherited. If it is packed, I am afraid there will be more packaging.
View reply reference
# 5th floor, | The shenzhen is creative. I never thought I could simplify the code like this... Thank you!
View reply reference
#6 floor | Terry Sun "handles exceptions in a consistent way for all working threads, such as notifying the main thread"
========================================================== ========
When I see this sentence, I know that multiple methods may be represented by one ThreadStart. If the method has parameters to be passed, is this method of LZ thread safe?
View reply reference
#7 floor, | yukai is good
View reply reference
#8 floor | Gu Jian to Ahha:
It is better to wrap the things we need in Thread, such as Start () and Abort () to implement custom threads, capture exceptions, and perform unified control?
View reply reference
#9 Floor [main poster] | Ahha @ Gu Jian
You mean like this? View source
Print?
03 |
private Thread thread; |
04 |
public MyThread(ThreadStart start) |
06 |
this.thread = new Thread(start); |
This is not acceptable. Thread exceptions can be solved simply by using try/catch Start.
Besides, I think that since. NET provides a complete set of Thread mechanisms, we can use the existing mechanisms. I think it is a bit complicated to introduce various methods for packaging Thread.
View reply reference
# Floor 10 [main poster] | Ahha @ Terry Sun
Thread security is an interesting topic that I did not cover here. However, I think each Worker thread is responsible for the thread security issues of the variables it references.
For thread conversion with parameters, same as above: view source
Print?
01 |
static ParameterizedThreadStart SafeThread(ParameterizedThreadStart threadStart) |
11 |
// TODO, handler exception, |
12 |
// Notify the main thread and stop this thread gracefully. |
You can also directly call the preceding non-parameter thread Conversion Function: view source.
Print?
1 |
static ParameterizedThreadStart SafeThread(ParameterizedThreadStart threadStart) |
3 |
return (obj) => SafeThread(() => threadStart(obj))(); |
View reply reference
#11 floor | what is the situation of the vineyard de hodgedge? Multiple Threads need to be created in different places, and the thread Exception Handling Mechanism will be the same?
View reply reference
#, September 28, | the code is very detailed and you need to consider some information for your control.
I think it is unnecessary to encapsulate exceptions,
However, if you want to have a better understanding, you should go to hang Shan.
In fact, the OS manages exceptions through SEH, but we cannot see this content on the upper layer. The code written is simple on the surface, but it is actually the same.
You can continue to explore...
View reply reference
#14 floor, | solitary sword public void Start ()
{
Try
{
This. thread. Start ();
}
// These exceptions must be handled independently.
Catch (ThreadAbortException)
{
Thread. ResetAbort ();
}
Catch (Exception e)
{
Console. WriteLine (e );
}
}
At the same time, you also need to consider the problem of multithreading. Pai_^
View reply reference
# 15f [main poster] | Ahha @ Gu Jian
Making user encoding simple is also a major purpose of encapsulation. What form is used is a balance between its benefits and disadvantages.
Thread encapsulation is an interesting topic. Are you interested in writing such an article?
View reply reference
# 16th floor, | Gu Jian
Hey, the guys in the school have already written the related content,
Http://kb.cnblogs.com/page/42528/