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 ...
随机推荐
- Go 实现 soundex 算法
[转]http://www.syyong.com/Go/Go-implements-the-soundex-algorithm.html SOUNDEX 返回由四个字符组成的代码 (SOUNDEX) ...
- 【BZOJ2253】纸箱堆叠 [CDQ分治]
纸箱堆叠 Time Limit: 30 Sec Memory Limit: 256 MB[Submit][Status][Discuss] Description P 工厂是一个生产纸箱的工厂. 纸 ...
- 51nod 扔盘子
题目传送门 这道题一开始写了n方的算法 果不其然 它T了 所以就想想o(n)的算法 写不出来 就像sbzhq学习了一下 这道题啊 要维护一下从深度1到n每一段的最小值以及他的位置 然后就暴力搞一搞就o ...
- 【CF1027F】Session in BSU(dsu,基环树)
题意:给出n场考试,每场考试有2天可以通过(第ai与bi天).每天最多参加一场考试,现在要求所有考试全部通过的最小天数 n<=1e6,1<=a[i]<b[i]<1e9 思路:F ...
- 【洛谷 P1896】[SCOI2005]互不侵犯(状压dp)
题目链接 题意:在N×N的棋盘里面放K个国王,使他们互不攻击,共有多少种摆放方案.国王能攻击到它上下左右,以及左上左下右上右下八个方向上附近的各一个格子,共8个格子. 这是道状压\(DP\)好题啊.. ...
- 卡片选项页面 JTabbedPane 的使用
package first; import javax.swing.*; import java.awt.*; import java.awt.event.*; class TtpDemo exten ...
- linux下su和su - 的区别
linux使用中常会使用su来切换用户 使用su切换为tom用户 [root@bogon ~]# su tom[tom@bogon root]$ [tom@bogon root]$ pwd/root ...
- 架构妄想:AJAX + REST
William Vambenepe的最新文章,AJAX + REST是最新的架构妄想,让我们回想起了一个具有15年历史的架构,它曾被寄期望对Web产生革命性的影响. 在该架构里,Web服务器将返回包含 ...
- C# WinForm开发 取消窗体关闭按钮
//禁用窗体的关闭按钮 private const int CP_NOCLOSE_BUTTON = 0x200; protected override CreateParams CreateParam ...
- React Native - 1 Windows下的环境配置(Windows+Android)
参考:https://facebook.github.io/react-native/docs/getting-started.html(要FQ) 网站上建议使用Chocolatey去配环境, ...