[英]Delegate.BeginInvoke Callback Blocking Calling Thread?
由于我对异步编程不是特别熟悉,因此我不确定如何处理此问题。 我有一个循环,它调用委托的BeginInvoke方法。 当执行委托的回调时,循环将停止执行(不应执行)。 我猜它正在运行的线程以某种方式被阻塞了,但我确实不确定。 这是代码的简化版本:
public class TestClass
{
private readonly IService service;
private delegate void TestDelegate();
private bool conditionIsMet = true;
public TestClass( IService service )
{
this.service = service;
}
public void PerformTask()
{
while ( conditionIsMet )
{
var testDelegate = new TestDelegate( service.DoSomething );
testDelegate.BeginInvoke( TestCallback, null );
Thread.Sleep( 1 );
}
}
private void TestCallback( IAsyncResult result )
{
var asyncResult = ( AsyncResult ) result;
var testDelegate = ( TestDelegate ) asyncResult.AsyncDelegate;
testDelegate.EndInvoke( asyncResult );
// After exiting this method the loop in PerformTask() ceases to execute.
// Is it being blocked here somehow?
}
}
实际上,代码还有很多,但据我所知,这里涉及的所有基本组件都在这里。 在上面的代码示例中,我在其中添加了注释,以指示代码执行的最后位置(无论如何,在VS调试器中)。
我假设我在进行委托异步调用的方式上犯了一些根本性的错误,但是我找不到任何向我解释它的文档。 知道为什么会这样吗?
更新
作为进一步测试的一部分,我在没有EndInvoke调用的情况下尝试了此操作(我知道,实际上是个坏主意),但是行为没有改变-它仍然无法继续执行循环。
我认为对我来说还可以。 您是否在控制台应用程序中运行它?
您需要停止该退出。
class Program
{
static void Main(string[] args)
{
TestClass t = new TestClass(new Service());
t.PerformTask();
Console.ReadKey();
}
}
public class Service : IService
{
public void DoSomething()
{
Console.WriteLine("Doing something");
}
}
public class TestClass
{
private readonly IService service;
private delegate void TestDelegate();
private bool conditionIsMet = true;
public TestClass(IService service)
{
this.service = service;
}
public void PerformTask()
{
while (conditionIsMet)
{
var testDelegate = new TestDelegate(service.DoSomething);
testDelegate.BeginInvoke(TestCallback, null);
Thread.Sleep(1);
}
}
private void TestCallback(IAsyncResult result)
{
var asyncResult = (AsyncResult)result;
var testDelegate = (TestDelegate)asyncResult.AsyncDelegate;
testDelegate.EndInvoke(asyncResult);
// After exiting this method the loop in PerformTask() ceases to execute.
// Is it being blocked here somehow?
}
}
public interface IService
{
void DoSomething();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.