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
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:
[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
<?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 ...
随机推荐
- 【bzoj1911-[Apio2010]特别行动队】斜率优化
[题目描述] 有n个数,分成连续的若干段,每段的分数为a*x^2+b*x+c(a,b,c是给出的常数),其中x为该段的各个数的和.求如何分才能使得各个段的分数的总和最大. [输入格式] 第1行:1个 ...
- 【spoj8222-Substrings】sam求子串出现次数
http://acm.hust.edu.cn/vjudge/problem/28005 题意:给一个字符串S,令F(x)表示S的所有长度为x的子串中,出现次数的最大值.求F(1)..F(Length( ...
- vue this.$router.push 页面不刷新
解决办法: 使用 watch,观察路由,发生变化重新获取数据 <script> export default { data() { return { data: {} } }, metho ...
- Educational Codeforces Round 40 A B C D E G
A. Diagonal Walking 题意 将一个序列中所有的\('RU'\)或者\('UR'\)替换成\('D'\),问最终得到的序列最短长度为多少. 思路 贪心 Code #include &l ...
- 【FIRST USE】第一次用git把代码上传到github
第一次使用某个东西总是充满了伤痛,我第一次用sed的时候,毁掉了我的所有源代码,第一次用git的时候一直提示不正确,后来解决了问题,便记录下来. 首先说明我的环境,我用的是虚拟机,上面运行的64位的c ...
- Newtonsoft.Json 序列化和反序列化 以及时间格式
1.JSON序列化 string JsonStr= JsonConvert.SerializeObject(Entity); eg: A a=new A(); a.Name="Elain ...
- 杀掉MYSQL死锁进程
vi /usr/local/killmysqlprocess.sh #!/bin/bash #*/1 * * * * /usr/local/src/killmysqlprocess.sh backdi ...
- jquery事件之select选中事件
根据select下拉列表选中的不同选项执行不同的方法,工作中经常会用到,这里就要用到Jquery的select选中事件 这里给select加一个叫label_id的id,然后通过id选择器找到这个节点 ...
- 变量与指针 --- WalMart 寄存箱设计者不懂计算机
一.场景: 今天星期天,难得公司售后同事很给力,项目运行正常,无运维事务需要处理.于是满足堂客(湖南人称老婆)很久来的心愿 陪其逛街(这里要惭愧 检讨作为IT码农常常容易忽略身边的人.大声疾呼:“码农 ...
- centeros7的redis-cli命令不生效解决方法(亲测)
如果你已经安装了redis服务器,并且已经启动,但是redis-cli命令无法生效,分析,命令未加入环境变量.那就给redis命令加入环境变量中: 注意点:redis安装目录会有不同,注意下面的PAT ...