当前位置: 首页 > news >正文

C# Windows Azure Queue的操作

Step 1 :


安装windows Azure package


Step 2 : 

配置文件增加:


 <appSettings>
    <add key="StorageConnectionString" value="your connection string" />
  </appSettings>




Step 3 :


using this Azure class


namespace Axe.AzureStorage
{
    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Threading;
    using System.Threading.Tasks;


    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Queue;


    public class WinAzureStorageAsync
    {
        private readonly CloudQueue queue;
        private readonly int timeoutSecond;
        private CloudQueueClient queueClient;
        public CloudQueueClient QueueClient
        {
            get
            {
                if (this.queueClient != null)
                    return this.queueClient;


                var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                this.queueClient = storageAccount.CreateCloudQueueClient();
                return this.queueClient;
            }
        }


        since each time fetch message is not a block operation
        so need to set a timeout & keep fetching , default is 3 seconds
        private const int SleepInterval = 100;


        public WinAzureStorageAsync(string queueName, int timeoutSecond = 3)
        {
            queueName = queueName.ToLower();
            this.queue = this.QueueClient.GetQueueReference(queueName);
            if (!this.QueueClient.GetQueueReference(queueName).Exists())
            {
                this.queue.CreateIfNotExists();
            }


            this.timeoutSecond = timeoutSecond;
        }


        public async Task<CloudQueueMessage> GetMessage()
        {
            CloudQueueMessage message = null;


            var passed = 0;
            
            while (message == null && passed < this.timeoutSecond * 10 * SleepInterval)
            {
                message = await this.queue.GetMessageAsync();
                Thread.Sleep(SleepInterval);
                passed += SleepInterval;
            }
            if (message == null)
            {
                throw new TimeoutException("Get Message From Azure Queue Operation has been timeout");
            }
            await this.queue.DeleteMessageAsync(message);


            return message;
        }


        public async Task<string> GetString()
        {
            var msg = await this.GetMessage();
            return msg.AsString;
        }


        public async Task<byte[]> GetBytes()
        {
            var msg = await this.GetMessage();
            return msg.AsBytes;
        }


        public T Get<T>() where T : new()
        {
            var bytes = this.GetBytes();
            return this.BytesToT<T>(bytes.Result);
        }


        public async Task Add(string message)
        {
            await this.queue.AddMessageAsync(new CloudQueueMessage(message));
        }


        public async Task Add(byte[] bytes)
        {
            await this.queue.AddMessageAsync(new CloudQueueMessage(bytes));
        }


        public void Add<T>(T obj) where T : new()
        {
            var bytes = this.TToBytes(obj);
            this.Add(bytes);
        }


        /// <summary>
        /// Note : this operation make takes around 40 seconds to complete, reference here:
        /// http://msdn.microsoft.com/library/azure/dd179387.aspx
        /// </summary>
        /// <returns></returns>
        public async Task DeleteIfExists()
        {
            await this.queue.DeleteIfExistsAsync();
        }


        public async Task<bool> IsExist(string queueName)
        {
            queueName = queueName.ToLower();
            return await this.QueueClient.GetQueueReference(queueName).ExistsAsync();
        }


        public void ClearMessage()
        {
            this.queue.Clear();
        }


        private T BytesToT<T>(byte[] bytes)
        {
            using (var ms = new MemoryStream())
            {
                ms.Write(bytes, 0, bytes.Length);
                var bf = new BinaryFormatter();
                ms.Position = 0;
                var x = bf.Deserialize(ms);
                return (T)x;
            }
        }


        private byte[] TToBytes<T>(T obj)
        {
            var bf = new BinaryFormatter();
            using (var ms = new MemoryStream())
            {
                bf.Serialize(ms, obj);
                return ms.ToArray();
            }
        }
    }
}


相关文章:

  • 移动设备管理(MDM)与OMA(OTA)DM协议向导(二)——WAP协议(1)
  • Submit disabled Dropdown
  • Validation failed for one or more entities. See 'EntityValidationErrors' property for more details
  • [Windows编程] 如何判断操作系统是64位还是32位
  • 使用Roslyn动态编译和执行
  • 利用Windows7内置功能管理虚拟磁盘
  • 使用cecil 完成 code injection
  • 善用属性
  • SQLServer任意列之间的聚合
  • [编程技巧] 巧用CPU缓存优化代码:数组 vs. 链表
  • 保存Bitmap到内存流中引发“GDI+中发生一般性错误”
  • Asp.net Mvc使用PagedList分页
  • [Web开发] PSD 转换成HTML/CSS 的工具网站
  • 算法练习--整数拆分为素数乘积
  • 算法练习--卡片游戏
  • [微信小程序] 使用ES6特性Class后出现编译异常
  • css布局,左右固定中间自适应实现
  • Python学习笔记 字符串拼接
  • RxJS 实现摩斯密码(Morse) 【内附脑图】
  • SegmentFault 社区上线小程序开发频道,助力小程序开发者生态
  • 关于 Linux 进程的 UID、EUID、GID 和 EGID
  • 基于web的全景—— Pannellum小试
  • 前端性能优化——回流与重绘
  • 驱动程序原理
  • 少走弯路,给Java 1~5 年程序员的建议
  • 视频flv转mp4最快的几种方法(就是不用格式工厂)
  • 一、python与pycharm的安装
  • PostgreSQL之连接数修改
  • SAP CRM里Lead通过工作流自动创建Opportunity的原理讲解 ...
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • #FPGA(基础知识)
  • #调用传感器数据_Flink使用函数之监控传感器温度上升提醒
  • #我与Java虚拟机的故事#连载12:一本书带我深入Java领域
  • #我与Java虚拟机的故事#连载13:有这本书就够了
  • $.ajax()
  • (12)目标检测_SSD基于pytorch搭建代码
  • (Git) gitignore基础使用
  • (Redis使用系列) SpirngBoot中关于Redis的值的各种方式的存储与取出 三
  • (翻译)Entity Framework技巧系列之七 - Tip 26 – 28
  • (收藏)Git和Repo扫盲——如何取得Android源代码
  • (转)c++ std::pair 与 std::make
  • .apk文件,IIS不支持下载解决
  • .gitattributes 文件
  • .NET 8 编写 LiteDB vs SQLite 数据库 CRUD 接口性能测试(准备篇)
  • .NET Framework杂记
  • .net oracle 连接超时_Mysql连接数据库异常汇总【必收藏】
  • .NET 解决重复提交问题
  • .NET版Word处理控件Aspose.words功能演示:在ASP.NET MVC中创建MS Word编辑器
  • .NET简谈互操作(五:基础知识之Dynamic平台调用)
  • .NET中 MVC 工厂模式浅析
  • /etc/sudoers (root权限管理)
  • @Query中countQuery的介绍
  • [ 渗透测试面试篇 ] 渗透测试面试题大集合(详解)(十)RCE (远程代码/命令执行漏洞)相关面试题
  • [.NET]桃源网络硬盘 v7.4
  • [20181219]script使用小技巧.txt