在Windows Phone 7(C#)上将事件转为异步/阻止调用 [英] Turn event into a async/blocking call on Windows Phone 7 (C#)

查看:131
本文介绍了在Windows Phone 7(C#)上将事件转为异步/阻止调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我先前提出这个问题,但忘记了提到一些约束,这是适用于Silverlight 4和C#4的Windows Phone 7.1(Mango),它缺少 System.Threading.Tasks await <我要求再次希望一个原生解决方案没有第三方库如 this 。)

(I asked this question earlier, but had forgotten to mention some constraints. This is for Windows Phone 7.1 (Mango) with Silverlight 4 and C# 4, which lacks System.Threading.Tasks, await and more. I'm asking again in hope for a native solution without 3rd party libs like this.)

我包装一个库供我自己使用。要获得一定的属性,我需要等待一个事件,这会很快的火灾。

I'm wrapping a library for my own use. To get a certain property I need to wait for an event, which fires pretty quick. I'm trying to wrap that into a blocking call.

基本上,我要转动

void Prepare()
{
    foo = new Foo();
    foo.Initialized += OnFooInit;
    foo.Start();
}
string Bar
{
    return foo.Bar;  // Only available after OnFooInit has been called.
}

进入

string GetBarWithWait()
{
    foo = new Foo();
    foo.Initialized += OnFooInit;
    foo.Start();
    // Wait for OnFooInit to be called and run, but don't know how
    return foo.Bar;
}

如何才能最好地实现?

推荐答案

您可以这样做:

string GetBarWithWait()
{
    foo = new Foo();

    using (var mutex = new ManualResetEvent(false))
    {
        foo.Initialized += (sender, e) => 
        {
            try
            {
                OnFooInit(sender, e);
            }
            finally
            {
                mutex.Set();
            }
        }

        foo.Start();

        mutex.WaitOne();
    }

    return foo.Bar;
}

但你必须确定Foo会调用初始化事件,无论发生什么。否则,你将永远阻止线程。如果Foo有某种错误事件处理程序,请订阅它以避免阻塞你的线程:

But you have to be absolutely certain that Foo will call the Initialized event no matter what happens. Otherwise, you'll block the thread forever. If Foo has some kind of error event handler, subscribe to it to avoid blocking your thread:

string GetBarWithWait()
{
    foo = new Foo();

    using (var mutex = new ManualResetEvent(false))
    {
        foo.Error += (sender, e) => 
        {
            // Whatever you want to do when an error happens
            // Then unblock the thread
            mutex.Set();
        }

        foo.Initialized += (sender, e) => 
        {
            try
            {
                OnFooInit(sender, e);
            }
            finally
            {
                mutex.Set();
            }
        }

        foo.Start();

        mutex.WaitOne();
    }

    return foo.Bar;
}

这篇关于在Windows Phone 7(C#)上将事件转为异步/阻止调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆