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. 【BZOJ2301】【HAOI2011】Problem b [莫比乌斯反演]

    Problem b Time Limit: 50 Sec  Memory Limit: 256 MB[Submit][Status][Discuss] Description 对于给出的n个询问,每次 ...

  2. 【BZOJ1101】Zap [莫比乌斯反演]

    Zap Time Limit: 10 Sec  Memory Limit: 162 MB[Submit][Status][Discuss] Description 对于给定的整数a,b和d,有多少正整 ...

  3. 设置session过期时间

    1如下是登录注册和记住密码的功能: # -*- coding: utf-8 -*- def cms_login(request): if request.method == 'GET': return ...

  4. CentOS 7 安装python3.6.1

    说明:CentOS 7最小化安装,默认Python 2.7 ,开发需要安装python3.6.1 . 1.检查python版本 [root@bogon ~]# python -VPython 2.7. ...

  5. shell命令行混合进制计算器smartbc

    需要简单的计算的时候,不想用GUI的计算器,能在shell下直接计算就最好了 查了下,有个东西叫 bc,  具体的使用就不赘述了,可以运行bc,然后进去计算,也可以echo传递过去,大概是像这样 ec ...

  6. VS mfc MessageBox() 和 AfxMessageBox()

    转载:http://blog.csdn.net/phenixyf/article/details/41744039 一.MessageBox()用法 1.函数原型 Messagebox函数在Win32 ...

  7. crontab执行脚本失败问题

    如果脚本在终端执行正常,而在crontab里执行失败, 一般跟root用户无关,而是和系统变量有关,一般加上绝对路径执行java命令即可: /usr/java/jdk/bin/java xxx.jar

  8. 记录一次WebService使用的经历

    于业务需要,需要和第三方对接一些接口,但是问题是,他们的接口提供是webservice的,本人只精通restful接口(也就是说我比较年轻^-^).好在对面人特别奈斯,一顿指导我,感谢. 废话不多说了 ...

  9. Nodejs解决所有跨域请求

    Nodejs解决所有跨域请求 app.use(function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); ...

  10. [jquery]判断checkbox是否选中

    if ($("#id").is(":checked"))