c# - 我等不及任务完成
问题描述
我ManagementEventWatcher
用来监控一个进程。如果进程被打开或修改,我会运行一个任务。我想await
在主线程中完成任务(请注意,任务在事件线程中初始化,并从那里开始。但我想form_load
在任务完成之前停止代码执行)我为此尝试了几种方法,但没有一种方法有效。这是一。
static string summonerId = null;
static Task summonerIdTask;
private async void Form1_Load(object sender, EventArgs e)
{
string tick = "0.1";
string processName = "LeagueClient.exe";
string query = String.Format(@"
SELECT *
FROM __InstanceOperationEvent
WITHIN {0}
WHERE TargetInstance ISA 'Win32_Process'
AND TargetInstance.Name = '{1}'", tick, processName
);
string scope = @"\\.\root\CIMV2";
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += new EventArrivedEventHandler(OnEventArrived);
watcher.Start();
summonerIdTask.Wait();
}
// Detect when the process is running/closed/modificated.
private static void OnEventArrived(object sender, EventArrivedEventArgs e)
{
summonerIdTask = new Task(() => getSummonerId());
// If process is closed.
if (e.NewEvent.ClassPath.ClassName.Contains("InstanceDeletionEvent"))
summonerId = null;
// If summonerName is null
if (summonerId == null && !summonerIdTask.Status.Equals(TaskStatus.Running))
// If process is open or is modificated.
if (e.NewEvent.ClassPath.ClassName.Contains("InstanceCreationEvent"))
summonerIdTask.Start();
else
summonerIdTask.Start();
}
static LCUConnector connect;
static LCUEndpoints api;
static async void getSummonerId()
{
connect = new LCUConnector();
api = new LCUEndpoints(connect);
summonerId = JObject.Parse(await api.getSession())["summonerId"].ToString();
Console.WriteLine("1");
}
等待任务完成并将其发送到form_load
线程的正确方法是什么?
解决方案
推荐阅读
- typescript - 在 TypeScript 中调用联合类型的函数和构造函数
- locust - events.request_success += test_success_handle TypeError: += 不支持的操作数类型: 'EventHook' 和 'function'
- aws-lambda - 被 CORS 阻止并且也无法使用 Amplify Functions 访问 REST API 端点
- javascript - 在 ES6 中对 import 语句和 export 语句中的所有文件进行分组
- javascript - 值不存在时如何根据cypress中的值检查复选框元素
- javascript - React-Native Android 方向
- netbeans - 在 NetBeans 中的拆分或克隆窗口上停止自动滚动
- java - 通过名单
在@RequestHeader Restapi - typescript - 如何创建 Jupyter Lab 扩展,将自定义按钮添加到 Jupyter Lab 笔记本的工具栏?
- opengl - 是否有任何机器只能支持 OpenGL 1.0(甚至不是 1.1)?