ExceptionHandler.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #if DOTNETCORE
  2. using System;
  3. using System.Threading;
  4. namespace OpenCvSharp.Internal
  5. {
  6. /// <summary>
  7. /// This static class defines one instance which than can be used by multiple threads to gather exception information from OpenCV
  8. /// Implemented as a singleton
  9. /// </summary>
  10. public static class ExceptionHandler
  11. {
  12. // ThreadLocal variables to save the exception for the current thread
  13. private static readonly ThreadLocal<bool> exceptionHappened = new ThreadLocal<bool>(false);
  14. private static readonly ThreadLocal<ErrorCode> localStatus = new ThreadLocal<ErrorCode>();
  15. private static readonly ThreadLocal<string> localFuncName = new ThreadLocal<string>();
  16. private static readonly ThreadLocal<string> localErrMsg = new ThreadLocal<string>();
  17. private static readonly ThreadLocal<string> localFileName = new ThreadLocal<string>();
  18. private static readonly ThreadLocal<int> localLine = new ThreadLocal<int>();
  19. /// <summary>
  20. /// Callback function invoked by OpenCV when exception occurs
  21. /// Stores the information locally for every thread
  22. /// </summary>
  23. public static readonly CvErrorCallback ErrorHandlerCallback =
  24. delegate (ErrorCode status, string funcName, string errMsg, string fileName, int line, IntPtr userData)
  25. {
  26. try
  27. {
  28. return 0;
  29. }
  30. finally
  31. {
  32. exceptionHappened.Value = true;
  33. localStatus.Value = status;
  34. localErrMsg.Value = errMsg;
  35. localFileName.Value = fileName;
  36. localLine.Value = line;
  37. localFuncName.Value = funcName;
  38. }
  39. };
  40. /// <summary>
  41. /// Registers the callback function to OpenCV, so exception caught before the p/invoke boundary
  42. /// </summary>
  43. public static void RegisterExceptionCallback()
  44. {
  45. IntPtr zero = IntPtr.Zero;
  46. IntPtr ret = NativeMethods.redirectError(ErrorHandlerCallback, zero, ref zero);
  47. }
  48. /// <summary>
  49. /// Throws appropriate exception if one happened
  50. /// </summary>
  51. public static void ThrowPossibleException()
  52. {
  53. if (CheckForException())
  54. {
  55. throw new OpenCVException(
  56. localStatus.Value,
  57. localFuncName.Value ?? "",
  58. localErrMsg.Value ?? "",
  59. localFileName.Value ?? "",
  60. localLine.Value);
  61. }
  62. }
  63. /// <summary>
  64. /// Returns a boolean which indicates if an exception occured for the current thread
  65. /// Reading this value changes its state, so an exception is handled only once
  66. /// </summary>
  67. private static bool CheckForException()
  68. {
  69. var value = exceptionHappened.Value;
  70. // reset exception value
  71. exceptionHappened.Value = false;
  72. return value;
  73. }
  74. }
  75. }
  76. #endif