前提・実現したいこと
現在C#でフォームアプリケーションを作成しています.
外部に物理ボタンを設置しており,それが押された場合に発火するイベントハンドラを作成したいです.
現状起こっている問題
コンストラクタ内でチェックを始めたいのですが,ボタンが押されるまで他の動作が完全にストップしてしまうという問題があります.
理想としては,メインの処理をやっている最中に,ボタンが押されたかどうかのチェックを非同期で行いたいです.
該当のソースコード
c#
1public class Hoge 2{ 3 static ButtonEvent _buttonEvent; 4 5 public Hoge() 6 { 7 var cts = new CancellationTokenSource(); 8 _buttonEvent = new ButtonEvent(code => PushedButton(code, cts)); 9 10 Task.WhenAll(_buttonEvent.Start(cts.Token)).Wait(); // ① 11 } 12 13 static void PushedButton(int eventCode, CancellationTokenSource cts) 14 { 15 // ボタンが押された時に行う処理 16 } 17} 18 19delegate void ButtonEventHandler(int eventCode); 20 21public class ButtonEvent 22{ 23 public event ButtonEventHandler _pushedButton; 24 25 public ButtonEvent(ButtonEventHandler pushedButton) 26 { 27 _pushedButton += pushedButton; 28 } 29 30 public Task Start(CancellationToken ct) 31 { 32 return Task.Run( () => EventLoop(ct) ); 33 } 34 35 public void EventLoop(CancellationToken ct) 36 { 37 while (!ct.IsCancellationRequested) 38 { 39 code = // ボタンが押されたら値を挿入する処理 40 41 _pushedButton(code); 42 } 43 } 44} 45
試したこと
上記ソースコードの①部分に,並列に行いたい処理を追加すれば,その処理を行なっている最中のみボタンのチェックが行えることがわかりました.
アプリケーション全体に渡ってチェックを適用させたい場合は,Program.cs
ファイル内で
c#
1static class Program 2{ 3 static ButtonEvent _buttonEvent; 4 5 [STAThread] 6 static void Main() 7 { 8 Application.EnableVisualStyles(); 9 Application.SetCompatibleTextRenderingDefault(false); 10 11 var cts = new CancellationTokenSource(); 12 _buttonEvent = new ButtonEvent(code => PushedButton(code, cts)); 13 14 Task.WhenAll( 15 _buttonEvent.Start(cts.Token), 16 Application.Run(new Form_MainConsol() 17 ); 18 } 19 20 static void PushedButton(int eventCode, CancellationTokenSource cts) 21 { 22 // ボタンが押された時に行う処理 23 } 24}
と書かなければいけないのでしょうか?
ボタンチェックの処理のみを非同期で行う方法はありませんか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/07 06:00
2018/07/07 06:33
2018/07/07 06:41
2018/07/07 07:06