Task-based Asynchronous Operation in WCF z
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
IAsyncResultasynchronous
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:
[ServiceContract]
public interface IMessage
{
[OperationContract]
Task<string> GetMessages(string msg);
}
With this simple contract, the implementation is just straight forward.
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
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
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):
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
<?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.
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的更多相关文章
- The Task: Events, Asynchronous Calls, Async and Await
The Task: Events, Asynchronous Calls, Async and Await Almost any software application today will lik ...
- CQRS, Task Based UIs, Event Sourcing agh!
原文地址:CQRS, Task Based UIs, Event Sourcing agh! Many people have been getting confused over what CQRS ...
- ABP .Net Core 调用异步方法抛异常A second operation started on this context before a previous asynchronous operation completed
1. 问题描述 最近使用ABP .Net Core框架做一个微信开发,同时采用了一个微信开发框架集成到ABP,在微信用户关注的推送事件里调用了一个async 方法,由于没有返回值,也没做任何处理,本 ...
- WCF z
终结点与服务寄宿 由于最近可能要使用WCF做开发,开始重读蒋金楠的<WCF全面解析>,并整理个人学习WCF的笔记. 蒋金楠的书是我的第一本WCF入门书,虽说硬着头皮啃下来了,但是原理内容太 ...
- [Compose] 11. Use Task for Asynchronous Actions
We refactor a standard node callback style workflow into a composed task-based workflow. For example ...
- Translate this app.config xml to code? (WCF) z
http://stackoverflow.com/questions/730693/translate-this-app-config-xml-to-code-wcf <system.servi ...
- 基于异步的MVC webAPI控制器
MVC – Task-based Asynchronous Pattern (TAP) – Async Controller and SessionLess Controller Leave a re ...
- .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 ...
- 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 ...
随机推荐
- [POJ2954&POJ1265]皮克定理的应用两例
皮克定理: 在一个多边形中.用I表示多边形内部的点数,E来表示多边形边上的点数,S表示多边形的面积. 满足:S:=I+E/2-1; 解决这一类题可能运用到的: 求E,一条边(x1,y1,x2,y2)上 ...
- 【洛谷 P4777】 【模板】扩展中国剩余定理(EXCRT)
注意一下:: 题目是 \[x≡b_i\pmod {a_i}\] 我总是习惯性的把a和b交换位置,调了好久没调出来,\(qwq\). 本题解是按照 \[x≡a_i\pmod {b_i}\] 讲述的,请注 ...
- bzoj 1293 贪心
首先我们可以将这道题看成一个数轴,数轴其中的某些点存在一些颜色,我们要选取最短的一段,使这段存 在所有颜色,那么我们使用指针i,j表示在j-i位置中包含的颜色,那么初值是0,0,我们先i++,同时添加 ...
- 使用dd命令克隆整个系统
神奇的ghost的原理是什么呢?不就是数据复制吗?Linux下的dd命令不就是最强大的数据复制工具! 既然如此,我为什么要使用g4l这样复杂的工具呢?一条dd命令不就可以帮我实现任意 ...
- Python学习笔记 - day3 - 数据类型及运算符
Python的数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频.网页等各种各样的数据,不同 ...
- mac废纸篓清空的心得、mac设置不睡眠不待机不锁屏、如何快速锁屏待机睡眠、mac重启、mac学习的必备软件-城
mac废纸篓清空: 1.使用废纸篓的清空废纸篓,清空所有包括被锁定的文件: 2.使用“磁盘工具”的“修复磁盘权限”,修复完成再操作清空废纸篓: 3.使用cleanmymac软件“垃圾清理”和“擦除器” ...
- 驱动模块和装模块的概念——Junit单元测试案例
驱动模块是用来模拟被测试模块的上一级模块,相当于被测模块的主程序.它接收数据,将相关数据传送给被测模块,启用被测模块,并打印出相应的结果. 桩模块(Stub)是指模拟被测试的模块所调用的模块,而不是软 ...
- 在一个ros包下怎么使用另外一个自定义ros包里的message
假设自定义消息包my_message_package https://answers.ros.org/question/206257/catkin-use-ros-message-from-anoth ...
- AC日记——[JSOI2008]火星人prefix bzoj 1014
1014 思路: 平衡树+二分答案+hash: 好了懂了吧. 代码: #include <cstdio> #include <cstring> #include <ios ...
- (3)webApi postman使用
https://www.getpostman.com/