Programming example of popular issues in WCF (4): How does a WCF client asynchronously call the WCF Service?

Source: Internet
Author: User
Tags net thread

Programming example of popular issues in WCF (4): How does a WCF client asynchronously call the WCF Service?

How to call WCF Service asynchronously?

[1] Problem description:

How does a WCF client asynchronously call the WCF Service?

How to call WCF Service asynchronously?

 

Many posts have been posted on the Forum about How to Implement Asynchronous calling of WCF.ArticleIncluding msdn, detailed learning materials and examples are provided.Code. However, a lot of information is too general, and the msdn example is a bit complicated. In our actual project, the requirement to be implemented is often very simple, that is, to Implement Asynchronous calls to the WCF Service operations on the client, that is, call the WCF Service asynchronously.

[2] data collection:

Here we will collect some useful references and problem connections for the asynchronous call of WCF. In fact, there are many posts about the asynchronous call of the WCF Service by the WCF client, but many discussions have taken a detour. What we want is a simple example of the asynchronous call of the WCF Service operation. Here are some valuable references:

    • How to: Call a WCF Service Operation Asynchronously
    • How to: call WCF Service Operations Asynchronously
    • ASP. NET calls WCF Asynchronously

[3] asynchronous call:

An important concept to be understood here is the asynchronous call mechanism, which is a very important knowledge point in. net. The callback concept is also used here .. In net, asynchronous calls actually use Asynchronous delegation. The method to be executed by the asynchronous delegate is submitted to the. NET thread pool, and the threads in the thread pool are used to execute asynchronous calls.

[4] solution:

After learning about the. NET asynchronous call mechanism, we can try to solve this problem. This is essentially the same. However, the encoding process is slightly different.

    1. Of course, the easiest thing to understand is that we write code to Implement Asynchronous calls.
    2. Secondly, Visual Studio 2008 provides this support. This is more convenient. I will give:

The sample process here is based on the Code asynchronously called by the handwritten client. For reference only. You can also use Visual Studio to complete this process.

[5] server code:

The implementation of the server code is very simple. Here we still use the early WCF Code to define an iwcfservice contract that contains an operation sayhello. The function of this operation is to accept a name parameter, then print the returned string to the client. For demonstration, the time information is printed here. The Code is as follows:

// 1. Service Contract
[Servicecontract (namespace ="Http://www.cnblogs.com/frank_xl/ ")]
Public interface iwcfservice
{
// Operation contract
[Operationcontract]
String sayhello (string name );

}
// 2. Service class, inherited interface. Implementation contract
Public class wcfservice: iwcfservice
{
// Method for implementing Interface Definition
Public String sayhello (string name)
{
Console. writeline ("Call operation at {0}", datetime. Now. tostring ("yyyy-mm-dd hh: mm: SS: ffff "));
Return string. Format ("Hello {0}", name );
}
}

[6] client code:

Most of the client's implementation code is no different from the previous one. For convenience, we can modify it based on the code generated by Visual Studio. Of course, you can rewrite it by yourself. The most important point here is the contract and method required to Implement Asynchronous calls.

[6.1] First, we need to implement a contract that supports asynchronous calls:

Public interface iwcfservice {
[System. servicemodel. operationcontractattribute (Action ="Http://www.cnblogs.com/frank_xl/IWCFService/SayHello", Replyaction ="Http://www.cnblogs.com/frank_xl/IWCFService/SayHelloResponse ")]
String sayhello (string name );

[Operationcontract (asyncpattern = true)]
Iasyncresult beginsayhello (string name, asynccallback callback, object asyncstate );

String endsayhello (iasyncresult result );
}

[6.2] client proxy classes supporting asynchronous calls:

We need to inherit this contract in our wcfclient proxy class and provide implementation of Asynchronous Operation calls. The specific code is as follows:

Public String sayhello (string name ){
Return base. Channel. sayhello (name );
}

Public iasyncresult beginsayhello (string name, asynccallback callback, object asyncstate)
{
Return channel. beginsayhello (name, callback, asyncstate );
}

Public String endsayhello (iasyncresult result)
{
Return channel. endsayhello (result );
}

[6.3] Test client code:

The client code is more important, that is, the asynchronous callback method. When we call the beginsayhello method, we do not need to wait for the result to return. We hope that, after calling the sayhello operation, WCF performs some necessary work, such as displaying the returned results or further processing the returned data. The callback function must be used here. You can also close the WCF client in the callback method to release resources.

The sample code is as follows:

/// <Summary>
/// This class is defined for WCF async call Test
/// </Summary>
Public class wcfclienttest
{
Static public wcfserviceclient wcfserviceproxy = NULL;
Static void main (string [] ARGs)
{
Console. foregroundcolor = consolecolor. Yellow;

wcfclienttest client = new wcfclienttest ();
wcfserviceproxy = new wcfserviceclient ("wshttpbinding_iwcfservice ");
string name = "Frank Xu lei";
console. writeline ("client async call begin at {0}", datetime. now. tostring ("yyyy-mm-dd hh: mm: SS: ffff");
// start to asynchronously call begin call
wcfserviceproxy. beginsayhello (name, client. oncompletion, null);

console. writeline ("press enter to exit... ");
console. Read ();

}
//// Callback method, callback Method
Void oncompletion (iasyncresult result)
{
String value = wcfserviceproxy. endsayhello (result );
Console. writeline ("returned value is {0} At {1}", value, datetime. now. tostring ("yyyy-mm-dd hh: mm: SS: ffff "));
Result. asyncwaithandle. Close ();
Wcfserviceproxy. Close ();
Console. writeline ("Asynchronous CILS is finished ");
}
}

 

[7] running result:

Start hostProgramAnd then run the WCF client. We can see the difference in time between the host and client for asynchronous call operations. The print window is as follows:

 

【Xu's blog]

【Author]:Frank Xu lei

【Website]:Http://www.frankxulei.com/

【Boke]:Http://www.cnblogs.com/frank_xl/

[Chinese Forum ]:Microsoft WCF Chinese Technology Forum
[English Forum ]:Microsoft WCF English Technical Forum

Programming example of popular issues in WCF (4): How does a WCF client asynchronously call the WCF Service?

How to call WCF Service asynchronously?

[1] Problem description:

How does a WCF client asynchronously call the WCF Service?

How to call WCF Service asynchronously?

 

Many posts have been posted on the Forum about How to Implement Asynchronous calling of WCF, and many articles have been discussed, including msdn's detailed learning materials and sample code. However, a lot of information is too general, and the msdn example is a bit complicated. In our actual project, the requirement to be implemented is often very simple, that is, to Implement Asynchronous calls to the WCF Service operations on the client, that is, call the WCF Service asynchronously.

[2] data collection:

Here we will collect some useful references and problem connections for the asynchronous call of WCF. In fact, there are many posts about the asynchronous call of the WCF Service by the WCF client, but many discussions have taken a detour. What we want is a simple example of the asynchronous call of the WCF Service operation. Here are some valuable references:

    • How to: Call a WCF Service Operation Asynchronously
    • How to: call WCF Service Operations Asynchronously
    • ASP. NET calls WCF Asynchronously

[3] asynchronous call:

An important concept to be understood here is the asynchronous call mechanism, which is a very important knowledge point in. net. The callback concept is also used here .. In net, asynchronous calls actually use Asynchronous delegation. The method to be executed by the asynchronous delegate is submitted to the. NET thread pool, and the threads in the thread pool are used to execute asynchronous calls.

[4] solution:

After learning about the. NET asynchronous call mechanism, we can try to solve this problem. This is essentially the same. However, the encoding process is slightly different.

    1. Of course, the easiest thing to understand is that we write code to Implement Asynchronous calls.
    2. Secondly, Visual Studio 2008 provides this support. This is more convenient. I will give:

The sample process here is based on the Code asynchronously called by the handwritten client. For reference only. You can also use Visual Studio to complete this process.

[5] server code:

The implementation of the server code is very simple. Here we still use the early WCF Code to define an iwcfservice contract that contains an operation sayhello. The function of this operation is to accept a name parameter, then print the returned string to the client. For demonstration, the time information is printed here. The Code is as follows:

// 1. Service Contract
[Servicecontract (namespace ="Http://www.cnblogs.com/frank_xl/ ")]
Public interface iwcfservice
{
// Operation contract
[Operationcontract]
String sayhello (string name );

}
// 2. Service class, inherited interface. Implementation contract
Public class wcfservice: iwcfservice
{
// Method for implementing Interface Definition
Public String sayhello (string name)
{
Console. writeline ("Call operation at {0}", datetime. Now. tostring ("yyyy-mm-dd hh: mm: SS: ffff "));
Return string. Format ("Hello {0}", name );
}
}

[6] client code:

Most of the client's implementation code is no different from the previous one. For convenience, we can modify it based on the code generated by Visual Studio. Of course, you can rewrite it by yourself. The most important point here is the contract and method required to Implement Asynchronous calls.

[6.1] First, we need to implement a contract that supports asynchronous calls:

Public interface iwcfservice {
[System. servicemodel. operationcontractattribute (Action ="Http://www.cnblogs.com/frank_xl/IWCFService/SayHello", Replyaction ="Http://www.cnblogs.com/frank_xl/IWCFService/SayHelloResponse ")]
String sayhello (string name );

[Operationcontract (asyncpattern = true)]
Iasyncresult beginsayhello (string name, asynccallback callback, object asyncstate );

String endsayhello (iasyncresult result );
}

[6.2] client proxy classes supporting asynchronous calls:

We need to inherit this contract in our wcfclient proxy class and provide implementation of Asynchronous Operation calls. The specific code is as follows:

Public String sayhello (string name ){
Return base. Channel. sayhello (name );
}

Public iasyncresult beginsayhello (string name, asynccallback callback, object asyncstate)
{
Return channel. beginsayhello (name, callback, asyncstate );
}

Public String endsayhello (iasyncresult result)
{
Return channel. endsayhello (result );
}

[6.3] Test client code:

The client code is more important, that is, the asynchronous callback method. When we call the beginsayhello method, we do not need to wait for the result to return. We hope that, after calling the sayhello operation, WCF performs some necessary work, such as displaying the returned results or further processing the returned data. The callback function must be used here. You can also close the WCF client in the callback method to release resources.

The sample code is as follows:

/// <Summary>
/// This class is defined for WCF async call Test
/// </Summary>
Public class wcfclienttest
{
Static public wcfserviceclient wcfserviceproxy = NULL;
Static void main (string [] ARGs)
{
Console. foregroundcolor = consolecolor. Yellow;

wcfclienttest client = new wcfclienttest ();
wcfserviceproxy = new wcfserviceclient ("wshttpbinding_iwcfservice ");
string name = "Frank Xu lei";
console. writeline ("client async call begin at {0}", datetime. now. tostring ("yyyy-mm-dd hh: mm: SS: ffff");
// start to asynchronously call begin call
wcfserviceproxy. beginsayhello (name, client. oncompletion, null);

console. writeline ("press enter to exit... ");
console. Read ();

}
//// Callback method, callback Method
Void oncompletion (iasyncresult result)
{
String value = wcfserviceproxy. endsayhello (result );
Console. writeline ("returned value is {0} At {1}", value, datetime. now. tostring ("yyyy-mm-dd hh: mm: SS: ffff "));
Result. asyncwaithandle. Close ();
Wcfserviceproxy. Close ();
Console. writeline ("Asynchronous CILS is finished ");
}
}

 

[7] running result:

Start the Host Program and run the WCF client. We can see the time difference between the host and client for asynchronous call operations. The following figure shows the print window:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.