ThreadPool异常问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ThreadPool异常问题相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadPoolException

class Program

static void Main(string[] args)


System.Threading.WaitCallback waitCallback = new WaitCallback(new Program().MakeException);
try

ThreadPool.QueueUserWorkItem(Wrap(waitCallback, "aa"));

catch (Exception e)
Console.Write(e.Message);


Console.ReadKey();



public void MakeException(object state)

throw new Exception("该方法抛出一个异常");

public static WaitCallback Wrap(System.Threading.WaitCallback callback, object state)

return new WaitCallback(
delegate

try

callback(state);

catch (Exception ex)

throw new Exception("aaaa");

);





请问如何能在Main函数中MakeException方法所抛出的异常 并打印出来??
我知道那个包装类 已经捕获到我的异常了,但那不是在主线程中,还是ThreadPool另起的线程。

参考技术A //已经修改了你的源代码,你可以看下
class Program

static void Main(string[] args)


System.Threading.WaitCallback waitCallback = new WaitCallback(new Program().MakeException);
try

ThreadPool.QueueUserWorkItem(Wrap(waitCallback, "aa"));

catch (Exception e)

Console.Write(e.Message);


Console.ReadKey();



public void MakeException(object state)

throw new Exception("该方法抛出一个异常");

public static WaitCallback Wrap(System.Threading.WaitCallback callback, object state)

return new WaitCallback(
delegate

try

callback(state);

catch (Exception ex)

//这个地方就捕获到你MakeException抛出的异常了
Console.WriteLine(ex.ToString());
//throw new Exception("aaaa");

);

pythonThreadpool线程池任务终止简单示例

需求

加入我们需要处理一串个位数(0~9),奇数时需要循环打印它;偶数则等待对应时长并完成所有任务;0则是错误,但不需要终止任务,可以自定义一些处理。

 

关键点

定义func函数处理需求

callback处理返回结果,只有偶数和0返回;奇数会一直执行;要控制线程池状态,则需要针对偶数和0时抛出异常,并捕获异常处理。

threadpool定义线程池并发

 

实现

# -*- coding: utf-8 -*-
from threadpool import makeRequests, ThreadPool
import time
from multiprocessing import Process

异常定义和特殊值(0)定义

class Finish(SyntaxWarning):
pass



class PauseInfo(SyntaxWarning):
pass


pause_num = 0
 

func函数定义

0时返回False,其他偶数返回True

def func(para):
if para == pause_num:
print(‘start for %d and wait %ds‘ % (para, 4))
time.sleep(4)
print(‘error bcs ‘,para)
return False

if para % 2 == 0:
print(‘start for %d and wait %ds‘ % (para, para))
time.sleep(para)
print(‘stop for‘, para)
return True

while True:
print(‘continue for‘, para)
time.sleep(para)
 

callback定义

def callback(request, result):
if result:
raise Finish
else:
raise PauseInfo
 

线程池处理

Finish标识任务完成,再次诱发异常退出线程池处理;

def main_thread(paras):
pool = ThreadPool(10)
requests = makeRequests(callable_=func, args_list=paras, callback=callback)
[pool.putRequest(req) for req in requests]
while True:
try:
pool.wait()
except Finish as e:
raise SystemExit
except PauseInfo as e:
print(‘Pause bcs %d but will continue‘ % pause_num)
except Exception as e:
print(‘Unknown error so will quit‘)
raise SystemExit
 

主函数起一个测试进程

if __name__ == ‘__main__‘:
while True:
s = input(‘Input number list to test and any other word to quit\n‘)
paras = []
for para in s:
if para.isnumeric():
paras.append(int(para))
else:
break

try:
thread_test = Process(target=main_thread, args=(paras,))
thread_test.start()
thread_test.join(timeout=20)
except TimeoutError as e:
print(‘task timeout‘)
except Exception as e:
print(‘unknow error:‘,e)
 

结果验证

 

处理108,看打印可以看到,1被循环处理,0处理的时候报错;8处理完毕则任务结束

Input number list to test and any other word to quit
108
continue for 1
start for 0 and wait 4s
start for 8 and wait 8s
continue for 1
continue for 1
continue for 1
error bcs  0
continue for 1
Pause bcs 0 but will continue
continue for 1
continue for 1
continue for 1
continue for 1
stop for 8
Input number list to test and any other word to quit













































































以上是关于ThreadPool异常问题的主要内容,如果未能解决你的问题,请参考以下文章

java ThreadPool 是如何设计处理线程异常场景的?

线程池 execute 异常

ThreadPool.QueueUserWorkItem引发的血案,线程池异步非正确姿势导致程序闪退的问题

深度解析Java线程池的异常处理机制

深度解析Java线程池的异常处理机制 #3

ThreadPool线程池源码解析