首页 > 解决方案 > 我等不及任务完成

问题描述

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线程的正确方法是什么?

标签: c#winformsasync-awaittasktask-parallel-library

解决方案


推荐阅读