XML Web Service的异步调用中可能的问题

本文探讨了ASP.NET Web Service中异步调用的问题,通过两个示例对比,展示了当客户端重复使用同一实例进行异步调用时出现的结果异常现象,并解释了原因。

1.服务(很简单)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebService1
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            System.Threading.Thread.Sleep(10000);
            return "Hello World";
        }
    }
}

2. 客户端(同样很简单)

大家可以比较下面两段代码的区别

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {


                client.HelloWorldCompleted += (o1, e1) =>
                {
                    Console.WriteLine("{0}:{1}",DateTime.Now, e1.Result);
                };

                client.HelloWorldAsync();
            }

            Console.Read();
        }
    }
}
--这一种情况,因为client每次都会创建一个新的实例,所以它的工作是合乎要求的,只返回了10个结果。

image

另外一个写法(这可能是很多朋友会使用的方式)

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {



            for (int i = 0; i < 10; i++)
            {

                client.HelloWorldCompleted += (o1, e1) =>
                {
                    Console.WriteLine("{0}:{1}",DateTime.Now, e1.Result);
                };

                client.HelloWorldAsync();
            }

            Console.Read();
        }
    }
}
虽然代码很合理,但是它的工作结果却很奇怪。它返回的结果有70行。
 

转载于:https://www.cnblogs.com/chenxizhang/archive/2009/12/19/1627936.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值