1.1与2.0异步调用Web服务简单示例

WebService代码:
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace 
= "http://tempuri.org/")]
[WebServiceBinding(ConformsTo 
= WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    
public Service () {

        
//如果使用设计的组件,请取消注释以下行 
        
//InitializeComponent(); 
    }

    [WebMethod]
    
public string HelloWorld(string strName) {
        
string strName1 = strName ?? "萝卜";
        
return strName1 + " 你好";
    }
}
1.1异步调用:因为没有VS2003,用#develop写的。
using System;
using MyService = ServiceTest.Service;

namespace ServiceTest
{
    
class MainClass
    {
        
static IAsyncResult iresult;
        
static MyService.Service service = new MyService.Service();
        
        
public static void Main(string[] args)
        {
            
//同步调用
            Console.WriteLine(service.HelloWorld(null));
            
            
//异步调用
            AsyncCallback callback = new AsyncCallback(CallBack);
            
            iresult
= service.BeginHelloWorld("萝卜青菜", callback, null);
            
            Console.Read();
        }
        
        
static void CallBack(IAsyncResult iar)
        {
            
if (object.Equals(null, iar))
            {
                Console.WriteLine(
"Null");
                
return;
            }
            
            
if (iar.IsCompleted)
            {
                Console.WriteLine(service.EndHelloWorld(iar));
            }
        }
    }
}
2.0异步调用:
using System;
using System.Collections.Generic;
using System.Text;

using myService = ServiceTest.FirstService;

namespace ServiceTest
{
    
class Program
    {
        
static void Main(string[] args)
        {
            Console.ForegroundColor 
= ConsoleColor.Green;
            
// 同步调用
            myService.Service service = new myService.Service();
            Console.WriteLine(service.HelloWorld(
null));

            
// 异步调用
            service.HelloWorldCompleted += delegate(object sender, myService.HelloWorldCompletedEventArgs e)
            {
                
if (object.Equals(null, e.Error))
                {
                    Console.WriteLine(e.Result);
                }
                
else
                {
                    Console.WriteLine(e.Error.Message);
                }
            };
            service.HelloWorldAsync(
"萝卜青菜");
            Console.Read();
        }
    }
}

posted on 2006-06-14 21:45  萝卜青菜  阅读(1158)  评论(2编辑  收藏  举报

导航