11using Python . Runtime ;
22using System ;
3+ using System . Threading ;
4+ using System . Threading . Tasks ;
35using UnityEngine ;
46using UnityEngine . UI ;
57
@@ -10,18 +12,48 @@ public class PlotRandom : MonoBehaviour
1012 {
1113 [ SerializeField ] private RawImage _rawImage ;
1214 [ SerializeField ] private Button _button ;
15+ private CancellationTokenSource cts ;
16+ private bool _executingPython = false ;
1317
1418 private void OnEnable ( )
1519 {
20+ cts = new CancellationTokenSource ( ) ;
1621 _button . onClick . AddListener ( PlotFig ) ;
1722 }
1823
1924 private void OnDisable ( )
2025 {
2126 _button . onClick . RemoveListener ( PlotFig ) ;
27+ cts . Cancel ( ) ;
28+ cts . Dispose ( ) ;
2229 }
2330
24- private void PlotFig ( )
31+ private async void PlotFig ( )
32+ {
33+ if ( _executingPython )
34+ {
35+ return ;
36+ }
37+
38+ _executingPython = true ;
39+ var state = PythonEngine . BeginAllowThreads ( ) ;
40+ try
41+ {
42+ var ( bytes , w , h ) = await Task . Run ( Plot , cts . Token ) ;
43+ LoadImage ( bytes , w , h ) ;
44+ }
45+ catch ( OperationCanceledException e ) when ( e . CancellationToken != cts . Token )
46+ {
47+ throw ;
48+ }
49+ finally
50+ {
51+ PythonEngine . EndAllowThreads ( state ) ;
52+ _executingPython = false ;
53+ }
54+ }
55+
56+ private ( byte [ ] , int , int ) Plot ( )
2557 {
2658 using ( Py . GIL ( ) )
2759 {
@@ -37,7 +69,7 @@ private void PlotFig()
3769 {
3870 span = new ReadOnlySpan < byte > ( ptr . ToPointer ( ) , w * h * s ) ;
3971 }
40- LoadImage ( span , w , h ) ;
72+ return ( span . ToArray ( ) , w , h ) ;
4173 }
4274 }
4375 }
0 commit comments