简体   繁体   English

使用.net 4中的任务等待事件触发

[英]Wait for an event to fire using tasks in .net 4

I have function A that calls function B from an external class that I cannot modify. 我具有从无法修改的外部类调用函数B的函数A。 Function B fires an event when completed on which I subscribed the doSomeStuff function. 函数B在完成订阅了doSomeStuff函数的事件后会触发一个事件。 I only want to finish Function A when doSomeStuff is finished. 我只想在doSomeStuff完成时完成功能A。 I can only use .Net 4, so no use of async etc.. I currently have this setup which freezes my program; 我只能使用.Net 4,因此不能使用异步等。

static EventWaitHandle _WaitHandle = new AutoResetEvent(false);

public void functionA()
{
  functionB.completed += doSomeStuff;
  Task runFunctionB = Task.Factory.StartNew(() => { functionB(); });
  _WaitHandle.WaitOne(); 
}

public void doSomeStuff(object sender, EventArgs e)
{
  // do stuff
  WaitHandle.Set();
}

I would expect task runFunctionB to execute as a seperate thread and therefore ending at my doSomeStuff function, but it seems not to do anything...? 我希望任务runFunctionB可以作为单独的线程执行,因此以我的doSomeStuff函数结尾,但是似乎什么也没做...?

Instead of WaitHandle you can use TaskCompletionSource<T> and wait for TaskCompletionSource<T>.Task . 可以使用TaskCompletionSource<T>代替WaitHandle并等待TaskCompletionSource<T>.Task

TaskCompletionSource<object> completionSource = new TaskCompletionSource<object>();

public void functionA()
{
  functionB.completed += doSomeStuff;
  Task runFunctionB = Task.Factory.StartNew(() => { functionB(); });

  completionSource.Task.ContinueWith((result)=> 
  {
     //Do whatever
  });
}

public void doSomeStuff(object sender, EventArgs e)
{
    // do stuff
    completionSource.SetResult(null);
}

I can only use .Net 4, so no use of async etc.. 我只能使用.Net 4,因此不使用异步等。

That is a misconception. 那是一个误解。 You can use async-await in .Net 4.0 using BCL.Async nuget package given that you have Visual studio 2012 or higher still targeting .Net 4.0. 如果您具有仍面向.Net 4.0的Visual Studio 2012,则可以使用BCL.Async nuget包在.Net 4.0中使用async-await。

In which case you can await the Task. 在这种情况下,您可以等待任务。

public async Task functionA()
{
  functionB.completed += doSomeStuff;
  Task runFunctionB = Task.Factory.StartNew(() => { functionB(); });

  await completionSource.Task;
  //Do whatever; event is raised
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM