2

I'm using ManagementEventWatcher to monitor a process. If the process is opened or modified I run a task. I'd like to await for the task to be completed in the main thread (note that the task is initialized in the event thread, and it starts there. But I'd like to stop the code execution in the form_load till the task finishes) I tried several ways for this but none of them works. This is one.

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");
}

What'd be the correct way to wait for the task to be completed and send it to the form_load thread?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Omar
  • 374
  • 1
  • 14

0 Answers0