线程化多个异步调用 [英] Threading multiple async calls

查看:87
本文介绍了线程化多个异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Silverlight应用程序的一部分需要来自三个服务请求的数据.直到现在,我一直在链接请求,以便一个请求完成另一个请求的开始……直到链的末尾,在该行中我需要对数据进行处理.

Part of my Silverlight application requires data from three service requests. Up until now I've been chaining the requests so as one completes the other starts... until the end of the chain where I do what I need to do with the data.

现在,我知道那不是最好的方法.我一直在查看 AutoResetEvent (链接到MSDN示例)进行线程化,然后同步结果,但似乎无法使其与异步服务调用一起使用.

Now, I know thats not the best method(!). I've been looking at AutoResetEvent (link to MSDN example) to thread and then synchronize the results but cannot seem to get this to work with async service calls.

有人有任何理由怀疑这种方法吗?还是应该可行?代码示例非常感谢!

Does anyone have any reason to doubt this method or should this work? Code samples gratefully received!

推荐答案

看看这个例子:

将触发Completed事件,并在两个服务都返回后将"done"打印到Debug Output. 关键是等待AutoResetEvents发生在后台线程中.

Will fire Completed event and print 'done' to Debug Output once both services returned. Key thing is that waiting for AutoResetEvents happens in background thread.

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        Completed += (s, a) => { Debug.WriteLine("done"); };

        wrk.DoWork += (s, a) =>
            {
                Start();
            };

        wrk.RunWorkerAsync();
    }
    public event EventHandler Completed;

    private void Start()
    {
        auto1.WaitOne();
        auto2.WaitOne();

        Completed(this, EventArgs.Empty);
    }

    public AutoResetEvent auto1 = new AutoResetEvent(false);
    public AutoResetEvent auto2 = new AutoResetEvent(false);

    BackgroundWorker wrk = new BackgroundWorker();

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ServiceReference1.Service1Client clien = new SilverlightAsyncTest.ServiceReference1.Service1Client();

        clien.DoWorkCompleted += new EventHandler<SilverlightAsyncTest.ServiceReference1.DoWorkCompletedEventArgs>(clien_DoWorkCompleted);
        clien.DoWork2Completed += new EventHandler<SilverlightAsyncTest.ServiceReference1.DoWork2CompletedEventArgs>(clien_DoWork2Completed);

        clien.DoWorkAsync();
        clien.DoWork2Async();
    }

    void clien_DoWork2Completed(object sender, SilverlightAsyncTest.ServiceReference1.DoWork2CompletedEventArgs e)
    {
        Debug.WriteLine("2");
        auto1.Set();
    }

    void clien_DoWorkCompleted(object sender, SilverlightAsyncTest.ServiceReference1.DoWorkCompletedEventArgs e)
    {
        Debug.WriteLine("1");
        auto2.Set();
    }
}

这篇关于线程化多个异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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