Introduction

Though performance blocking and sluggishness are the tailbacks for any application, we can easily overcome these bottlenecks by using asynchronous programming. But old-style practice for asynchronous programming is not way easy enough to write, debug and maintain. So what is the contemporary approach??

Well, in my view, this is task based asynchronous programming, which is updated in .NET 4.5 through the use of keywords await and async. But what do async and await do? async and await are the way of controlling continuation. When a method uses the async keyword, it means it is an asynchronous method, which might have an await keyword inside, and if it has an await keyword, async will activate it. So, simply async activates the await, from which point, the asynchronous has been started. There is a nice explanation that has been given here.

In WCF, we can also consider an asynchronous operation while the service operation creates a delaying call. There are three ways to implement asynchronous operations:

  • Task-based asynchronous
  • Event-based asynchronous
  • IAsyncResult asynchronous

In this article, I am going to use task-based asynchronous operation since this is the most contemporary strategy.

Okay. Let’s move to the code.

Define and Implement Service

A very simple Service contract such as:

Hide   Copy Code
[ServiceContract]
public interface IMessage
{
[OperationContract]
Task<string> GetMessages(string msg);
}

With this simple contract, the implementation is just straight forward.

Hide   Copy Code
public class MessageService : IMessage
{
async Task<string> IMessage.GetMessages(string msg)
{
var task = Task.Factory.StartNew(() =>
{
Thread.Sleep(10000);
return "Return from Server : " + msg;
});
return await task.ConfigureAwait(false);
}
}

Here, the method is marked with the async keyword, which means it might use await keyword inside. It also means that the method will be able to suspend and then resume asynchronously at await points. Moreover, it points the compiler to boost the outcome of the method or any exceptions that may happen into the return type.

Service Hosting

Hide   Copy Code
class Program
{
static void Main(string[] args)
{
var svcHost = new ServiceHost(typeof (MessageService));
Console.WriteLine("Available Endpoints :\n");
svcHost.Description.Endpoints.ToList().ForEach
(endpoints=> Console.WriteLine(endpoints.Address.ToString()));
svcHost.Open();
Console.ReadLine();
}
}

Service Configuration

Hide   Shrink   Copy Code
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="Rashim.RND.WCF.Asynchronous.ServiceImplementation.MessageService">
<host>
<baseAddresses>
<add baseAddress="net.Tcp://localhost:8732/"/>
<add baseAddress="http://localhost:8889/"/>
</baseAddresses>
</host>
<endpoint address="Tcp" binding="netTcpBinding"
contract="Rashim.RND.WCF.Asynchronous.Services.IMessage"/>
<endpoint address="Http" binding="basicHttpBinding"
contract="Rashim.RND.WCF.Asynchronous.Services.IMessage">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.5"/></startup>
</configuration>

After configuring the service, we need to configure the client app to consume the service.

Define Client

A simple Console Application (Client):

Hide   Copy Code
class Program
{
static void Main(string[] args)
{
GetResult();
Console.ReadLine();
} private async static void GetResult()
{
var client = new Proxy("BasicHttpBinding_IMessage");
var task = Task.Factory.StartNew(() => client.GetMessages("Hello"));
var str = await task;
str.ContinueWith(e =>
{
if (e.IsCompleted)
{
Console.WriteLine(str.Result);
}
});
Console.WriteLine("Waiting for the result");
}
}

Client Configuration

Hide   Copy Code
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IMessage" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8889/Http" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IMessage"
contract="Rashim.RND.WCF.Asynchronous.Services.IMessage"
name="BasicHttpBinding_IMessage" />
</client>
</system.serviceModel>
</configuration>

Finally, proxy class is given below through which the client will consume the services.

Hide   Copy Code
public class Proxy : ClientBase<IMessage>, IMessage
{
public Proxy()
{
}
public Proxy(string endpointConfigurationName) :
base(endpointConfigurationName)
{
}
public Task<string> GetMessages(string msg)
{
return Channel.GetMessages(msg);
}
}

That’s it. Very easy stuff though.

最新文章

  1. Thinkphp3.2.3 执行query命令 包括在模板中使用&lt;php&gt; &lt;/php&gt;时 query的使用方法
  2. Tomcat端口被占用错误
  3. 51nod平均数
  4. 【Ubuntu日常技巧】VirtualBox多网卡路由配置,保障虚拟机连接上外网
  5. Web Service性能测试方案
  6. 软件测试 homework1
  7. 最近两场比赛 CF 285 &amp; TC 646
  8. Android基础知识巩固:关于PendingIntent和广播
  9. DELPHI中多线程知识【转】
  10. 如何在Crystal框架项目中内置启动MetaQ服务?
  11. DES/des3 加密程序
  12. JS 实现blob与base64互转
  13. C#winform窗体利用系统抓取关闭按钮事件
  14. C#将结构体和指针互转的方法
  15. with与上下文管理器
  16. Android开发:setAlpha()方法和常用RGB颜色表----颜色, r g b分量数值(int), 16进制表示 一一对应
  17. hdu1059 dp(多重背包二进制优化)
  18. window.open 和 location.href 区别
  19. Daily Scrum meeting 2015.11.9
  20. 开源自己实现一个.net rpc框架 - Machete.Rpc

热门文章

  1. 之江学院第0届校赛 qwb去面试 (找规律)
  2. shell脚本复制文件夹内容到另外的文件夹,如果存在则自动备份
  3. linux下新硬盘的自动检测及格式化--支持硬盘的热插拔处理
  4. For循环中不可以嵌套RDD操作
  5. Solidity 文档--目录
  6. python笔记-邮件发送(smtplib)【转载】
  7. flask的插件
  8. Bootstrap模态框垂直居中展示的方法
  9. iPhone手机关闭ios10自动更新
  10. [BZOJ4556][Tjoi2016&amp;Heoi2016]字符串 主席树+二分+倍增+后缀自动机