【问题标题】:IAsyncResult and Multithreading in .NET 3.5.NET 3.5 中的 IAsyncResult 和多线程
【发布时间】:2014-05-15 02:17:21
【问题描述】:

我想向远程服务发出多个请求,并且正在尝试异步/多线程方法。 对于并发部分,我会试试这个http://coding-time.blogspot.pt/2008/03/implement-your-own-parallelfor-in-c.html

IList<string> returnedValues = new List<string>();
int numberOfRequests = 5;
object sync = new object();
ParallelUtilities.For(0, numberOfRequests, delegate(int i)
{
    string response = string.Empty;
    try
    {
         try
            {
                Func<int, string> caller = CallService;
                IAsyncResult result = caller.BeginInvoke(i, null, null);
                Thread.Sleep(0);
                string returnValue = caller.EndInvoke(result);

                lock (sync)
                {
                    returnedValues.Add(returnValue);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Concat("ex: ", ex.Message, "stack:", ex.StackTrace));
            }
    });
}

还有服务调用

private string CallService(int index)
{
    string value;
    using (var channel = GetClientChannel<IService>("http://localhost:51383/Service/Service.svc"))
    {
        value = channel.GetValue(index);
    }
    return value + "for this index:" + index;
}

有没有更好的方法来做到这一点? IAsyncResult 如何在多线程中工作?

【问题讨论】:

    标签: multithreading web-services asynchronous .net-3.5


    【解决方案1】:

    替换

                IAsyncResult result = caller.BeginInvoke(i, null, null);
                Thread.Sleep(0);
                string returnValue = caller.EndInvoke(result);
    

                string returnValue = CallService(result);
    

    在线程池上启动代码然后立即等待它是没有意义的。这样做你会得到什么? Sleep 对我来说特别可疑。您尝试启动上下文切换,这只会增加额外的开销。

    IAsyncResult 如何在多线程中工作?

    两者没有关系。什么意思?

    【讨论】:

    • 我打算多次调用网络服务并将结果存储在一个变量中。如何使用异步方法和多线程使其工作?这甚至是一个好的实现选择吗?
    • 在 3.5 上,我会使用您的自定义 ParallelUtilities.For(没关系)。您使用的基本方法是可以的。您正在线程池上运行您的工作项。或者,您可以使用异步 IO,但这在 3.5 上很难,并且可能对您没有帮助。
    猜你喜欢
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 2019-02-17
    • 2011-08-15
    • 2016-12-19
    相关资源
    最近更新 更多