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.

Task-based Asynchronous Operation in WCF z的更多相关文章

  1. The Task: Events, Asynchronous Calls, Async and Await

    The Task: Events, Asynchronous Calls, Async and Await Almost any software application today will lik ...

  2. CQRS, Task Based UIs, Event Sourcing agh!

    原文地址:CQRS, Task Based UIs, Event Sourcing agh! Many people have been getting confused over what CQRS ...

  3. ABP .Net Core 调用异步方法抛异常A second operation started on this context before a previous asynchronous operation completed

    1.  问题描述 最近使用ABP .Net Core框架做一个微信开发,同时采用了一个微信开发框架集成到ABP,在微信用户关注的推送事件里调用了一个async 方法,由于没有返回值,也没做任何处理,本 ...

  4. WCF z

    终结点与服务寄宿 由于最近可能要使用WCF做开发,开始重读蒋金楠的<WCF全面解析>,并整理个人学习WCF的笔记. 蒋金楠的书是我的第一本WCF入门书,虽说硬着头皮啃下来了,但是原理内容太 ...

  5. [Compose] 11. Use Task for Asynchronous Actions

    We refactor a standard node callback style workflow into a composed task-based workflow. For example ...

  6. Translate this app.config xml to code? (WCF) z

    http://stackoverflow.com/questions/730693/translate-this-app-config-xml-to-code-wcf <system.servi ...

  7. 基于异步的MVC webAPI控制器

    MVC – Task-based Asynchronous Pattern (TAP) – Async Controller and SessionLess Controller Leave a re ...

  8. .NET 4.5 is an in-place replacement for .NET 4.0

    With the betas for .NET 4.5 and Visual Studio 11 and Windows 8 shipping many people will be installi ...

  9. Async/Await - Best Practices in Asynchronous Programming z

    These days there’s a wealth of information about the new async and await support in the Microsoft .N ...

随机推荐

  1. centos 防火墙关闭/开启

    从配置菜单关闭防火墙是不起作用的,索性在安装的时候就不要装防火墙查看防火墙状态:/etc/init.d/iptables status暂时关闭防火墙:/etc/init.d/iptables stop ...

  2. bzoj 2820 mobius反演

    学了一晚上mobius,终于A了一道了.... 假设枚举到i,质数枚举到p(程序里的prime[j]),要更新A=i*p的信息. 1. p|i    这时A的素数分解式中,p这一项的次数>=2. ...

  3. CDLinux 自动休眠功能的关闭方法

    CDLinux 自动休眠功能的关闭方法: 控制台下使用xset命令来完成. xset q  可以查看当前屏幕保护和电源管理的状态信息 具体设置时,常用的有以下参数: xset s  //这个参数设置屏 ...

  4. sublime text 2 学习(一):快捷键

    初用sublime text 2,还不错,不装任何插件,能很好的编辑javascript,css,html,很赞.整理一下快捷键:常用的比如Ctrl+S就不列了:而且只列举Windows的. Ctrl ...

  5. python中的scapy模块

    scapy模块是干嘛用的? 答:Scapy的是一个强大的交互式数据包处理程序(使用python编写).它能够伪造或者解码大量的网络协议数据包,能够发送.捕捉.匹配请求和回复包等等.它可以很容易地处理一 ...

  6. python 列表表达式、生成器表达式和协程函数

    列表表达式.生成器表达式和协程函数 一.列表表达式: 常规方式示例: egg_list=[] for i in range(100): egg_list.append("egg%s" ...

  7. MySQL MyISAM优化设置点滴

    先说一点问题:   Mysql中的InnoDB和MyISAM是在使用MySQL中最常用的两个表类型,各有优缺点.两种类型最主要的差别就是 InnoDB 支持事务处理与外键和行级锁.而MyISAM不支持 ...

  8. iOS推送原理和证书生成简介

    1. 推送流程: Provider: 我们自己的后台服务器: APNS: 苹果的消息推送服务器 (1) 当Provider有消息要推送给手机的时候,先将消息和deviceToken等字段发送到APNS ...

  9. 1.kafka的介绍

    kafka是一种高可用,高吞吐量,基于zookeeper协调的分布式发布订阅消息系统. 消息中间件:生产者和消费者 举个例子: 生产者:做馒头,消费者:吃馒头,数据流:馒头 如果消费者宕机了,吃不下去 ...

  10. python 多进程锁Lock和共享内存

    多进程锁 lock = multiprocessing.Lock() 创建一个锁 lock.acquire() 获取锁 lock.release() 释放锁 with lock: 自动获取.释放锁 类 ...