windowService中使用多线程

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessServices;
using Common.Entities;
using System.Configuration;
using System.Data;
using OrderMaster;
using System.Collections;
using System.Threading;

namespace DownloadItemEmialWinService
{
public class EmailSendManager
{
public static void SendEmail(string path, string fromEmail, string Smtp, string userName, string password)
{

//需要发送记录
List<DownloadItemLog> ListDownloadItemLog = DownloadItemLogManager.DownloadItemLogSendLogs();
List<ProcessDownLoadItemLine> pols = new List<ProcessDownLoadItemLine>();

foreach (DownloadItemLog item in ListDownloadItemLog)
{
ProcessDownLoadItemLine pol = new ProcessDownLoadItemLine(item,path,fromEmail,Smtp,userName,password);
pols.Add(pol);
}
ProcessDownLoadItemWithThread(pols);

}

/// <summary>
/// 根据分类Id查找当前分类下的所有原料信息
/// </summary>
/// <param name="ee"></param>
/// <param name="categroyCode"></param>
/// <returns></returns>
public static List<ApprovedPurchasePrice> GetItemByCategroyCode(ExcelEdit ee, string categroyCode, string categroyName, List<ApprovedPurchasePrice> appItem)
{
List<ApprovedPurchasePrice> itemList = appItem.FindAll(c => c.Item_Class_I == categroyCode);
ee.CreateWorkSheet(categroyName);
ee.WriteData(EblastToXls(itemList), 1, 1);
return itemList;
}

/// <summary>
/// 根据categroyCode生成对应的原料信息
/// </summary>
/// <param name="appItems"></param>
/// <returns></returns>
public static DataTable EblastToXls(List<ApprovedPurchasePrice> appItems)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Item_No", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Item_Name", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Purchase_Unit_Of_Measure_Name", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Item_Specification", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("StartDate", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("EndDate", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Unit_Price", Type.GetType("System.String")));

DataRow drTitle = dt.NewRow();
drTitle["Item_No"] = "原料编号";
drTitle["Item_Name"] = "原料名称";
drTitle["Purchase_Unit_Of_Measure_Name"] = "单位";
drTitle["Item_Specification"] = "原料规格";
drTitle["StartDate"] = "开始时间";
drTitle["EndDate"] = "结束时间";
drTitle["Unit_Price"] = "单价";
dt.Rows.Add(drTitle);

foreach (ApprovedPurchasePrice app in appItems)
{
DataRow dr = dt.NewRow();
dr["Item_No"] = app.Item_No;
dr["Item_Name"] = app.Item_Name;
dr["Purchase_Unit_Of_Measure_Name"] = app.Pur_Unit_of_Measure_Name;
if (!String.IsNullOrEmpty(app.Item_Specification))
{
dr["Item_Specification"] = app.Specification;
}
DateTime sdate;
DateTime edate;
if (app != null)
{
sdate = app.Starting_Date;
edate = app.Ending_Date;
}
else
{
sdate = DateTime.MaxValue;
edate = DateTime.MaxValue;
}
if (DateTime.Compare(Convert.ToDateTime(app.Starting_Date.ToString("HH:ss")), Convert.ToDateTime("0:00:00")) == 0)
{
dr["StartDate"] = app.Starting_Date.ToString("yyyy-MM-dd");
}
else
{
dr["StartDate"] = app.Starting_Date;
}
if (DateTime.Compare(Convert.ToDateTime(app.Ending_Date.ToString("HH:ss")), Convert.ToDateTime("0:00:00")) == 0)
{
dr["EndDate"] = app.Ending_Date.ToString("yyyy-MM-dd");
}
else
{
dr["EndDate"] = app.Ending_Date;
}
dr["Unit_Price"] = Utilities.Utility.FormatNumber(app.Unit_Price);

dt.Rows.Add(dr);
}
return dt;
}

/// <summary>
/// 从webService中获得所有的原料信息
/// </summary>
/// <param name="startDate"></param>
/// <returns></returns>
private static List<ApprovedPurchasePrice> GetItemInfo(DateTime startDate, DateTime endDate,string companyName,string unitCode)
{
//base.ResetWebService();
ApprovedPurchasePrice_Service apps = new ApprovedPurchasePrice_Service(companyName);

ApprovedPurchasePrice_Filter apfilter = new ApprovedPurchasePrice_Filter();
apfilter.Field = ApprovedPurchasePrice_Fields.Starting_Date;
apfilter.Criteria = "<=" + endDate.ToString("MM/dd/yyyy");

//获取过滤条件(结束时间)
ApprovedPurchasePrice_Filter apfilter1 = new ApprovedPurchasePrice_Filter();
apfilter1.Field = ApprovedPurchasePrice_Fields.Ending_Date;
apfilter1.Criteria = ">=" + startDate.ToString("MM/dd/yyyy");

ApprovedPurchasePrice_Filter apfilter2 = new ApprovedPurchasePrice_Filter();
apfilter2.Field = ApprovedPurchasePrice_Fields.Unit_Code;
apfilter2.Criteria = unitCode;

ApprovedPurchasePrice[] appList = apps.ReadMultiple(new ApprovedPurchasePrice_Filter[] { apfilter, apfilter1, apfilter2 }, "", 0);
return appList.ToList();
}

/// <summary>
/// 根据分类Id查找所有分类信息
/// </summary>
public class CategroyCodeComparer : IEqualityComparer<ApprovedPurchasePrice>
{
public bool Equals(ApprovedPurchasePrice source, ApprovedPurchasePrice dest)
{
return source.Item_Class_I == dest.Item_Class_I;
}

public int GetHashCode(ApprovedPurchasePrice obj)
{
return obj.Item_Class_I.GetHashCode();
}
}

#region 多线程处理
private static void ProcessDownLoadItemWithThread(List<ProcessDownLoadItemLine> pols)
{
int threadCount;
try
{
threadCount = int.Parse(System.Configuration.ConfigurationManager.AppSettings["threadCount"]);
}
catch
{
threadCount = 1;
}

MyThread thread = new MyThread(pols, threadCount);
System.Threading.ParameterizedThreadStart ptStart = new ParameterizedThreadStart(SubmitOrderToNAV);
thread.TryExcute(ptStart);
}

public class MyThread
{
private int _threadCount = 10;
private int _threadIndex = 0;
private List<ProcessDownLoadItemLine> _pols = null;

public MyThread(List<ProcessDownLoadItemLine> pols, int threadCount)
{
this._pols = pols;
this._threadCount = threadCount;
}

public void TryExcute(ParameterizedThreadStart ptStart)
{
Thread[] threadList = new Thread[_threadCount];

for (int i = 0; i < _pols.Count; i++)
{
if (threadList.Length > i)
{
threadList[i] = new Thread(ptStart);
threadList[i].Start(_pols[i]);
}
else
{
if (_threadIndex == _threadCount)
{
_threadIndex = 0;
}

while (threadList[_threadIndex].ThreadState == System.Threading.ThreadState.Running)
{
Thread.Sleep(1000);
}

threadList[_threadIndex] = new Thread(ptStart);
threadList[_threadIndex].Start(_pols[i]);
_threadIndex++;

}
}
}
}

private static void SubmitOrderToNAV(Object processOrderLine)
{
ProcessDownLoadItemLine pol = (ProcessDownLoadItemLine)processOrderLine;
bool send_flag = false;

if (pol!=null&&pol.DownloadItemLog!=null)
{
List<ApprovedPurchasePrice> appItem = GetItemInfo(pol.DownloadItemLog.StartDate.Value, pol.DownloadItemLog.EndDate.Value, pol.DownloadItemLog.CompanyName, pol.DownloadItemLog.UnitCode);

if (appItem.Count != 0)
{
List<ApprovedPurchasePrice> appCategroy = appItem.Distinct(new CategroyCodeComparer()).ToList();

ExcelEdit ee = new ExcelEdit();
ee.CreateExcel();
for (int i = appCategroy.Count - 1; i >= 0; i--)
{
ApprovedPurchasePrice app = (ApprovedPurchasePrice)appCategroy[i];
GetItemByCategroyCode(ee, app.Item_Class_I, app.Item_Class_I_Name, appItem);
}
ee.DeleteSheet("Sheet1");
string savePath = pol._path;
string fileName = pol.DownloadItemLog.UnitCode + pol.DownloadItemLog.StartDate.Value.ToString("yyyy-MM-dd") + pol.DownloadItemLog.EndDate.Value.ToString("yyyy-MM-dd") + ".xls";
savePath += fileName;
if (System.IO.File.Exists(savePath))
{
System.IO.File.Delete(savePath);
}
if (ee.SaveAs(savePath))
{
ee.Close();

ArrayList strList = new ArrayList();
strList.Add(savePath);

System.Text.StringBuilder sbContent = new System.Text.StringBuilder();
sbContent.Append(pol.DownloadItemLog.CompanyName + "<br>");
sbContent.Append("供应点:" + pol.DownloadItemLog.UnitCode + "<br>");
sbContent.Append("<br>");
sbContent.Append("开始时间:" + pol.DownloadItemLog.StartDate + "<br>");
sbContent.Append("结束时间" + pol.DownloadItemLog.EndDate + "<br>");
sbContent.Append("<br>");
sbContent.Append("Thanks.<br>");
send_flag = Utilities.EmailService.SendEmail(pol._fromEmail, pol.DownloadItemLog.EmailAddress, pol.DownloadItemLog.CompanyName + "/" + pol.DownloadItemLog.StartDate.Value.ToString("yyyy-MM-dd") + "/" + pol.DownloadItemLog.EndDate.Value.ToString("yyyy-MM-dd") + "/下载产品列表", sbContent.ToString(), pol._userName, pol._password, pol._Smtp, strList, "");

}
}

if (send_flag)
{
pol.DownloadItemLog.DownloadStatus = 1;
}
else
{
pol.DownloadItemLog.DownloadStatus = -1;
}

pol.DownloadItemLog.ModifyPerson = "EmailService";

DownloadItemLogManager.DownloadItemLogInsUpd(pol.DownloadItemLog);

}

}

public class ProcessDownLoadItemLine
{
public DownloadItemLog DownloadItemLog { get; set; }
public string _path { get; set; }
public string _fromEmail { get; set; }
public string _Smtp { get; set; }
public string _userName { get; set; }
public string _password { get; set; }
public ProcessDownLoadItemLine(DownloadItemLog dil, string path, string fromEmail, string Smtp, string userName, string password)
{
DownloadItemLog = dil;
_path = path;
_fromEmail = fromEmail;
_Smtp = Smtp;
_userName = userName;
_password = password;
}
}

#endregion

}
}

windowService中使用多线程的更多相关文章

  1. 细说.NET 中的多线程 (一 概念)

    为什么使用多线程 使用户界面能够随时相应用户输入 当某个应用程序在进行大量运算时候,为了保证应用程序能够随时相应客户的输入,这个时候我们往往需要让大量运算和相应用户输入这两个行为在不同的线程中进行. ...

  2. 细说.NET中的多线程 (二 线程池)

    上一章我们了解到,由于线程的创建,销毁都是需要耗费大量资源和时间的,开发者应该非常节约的使用线程资源.最好的办法是使用线程池,线程池能够避免当前进行中大量的线程导致操作系统不停的进行线程切换,当线程数 ...

  3. [转载]ArcGIS Engine 中的多线程使用

    ArcGIS Engine 中的多线程使用 原文链接 http://anshien.blog.163.com/blog/static/169966308201082441114173/   一直都想写 ...

  4. python中的多线程【转】

    转载自: http://c4fun.cn/blog/2014/05/06/python-threading/ python中关于多线程的操作可以使用thread和threading模块来实现,其中th ...

  5. 拒绝卡顿——在WPF中使用多线程更新UI

    原文:拒绝卡顿--在WPF中使用多线程更新UI 有经验的程序员们都知道:不能在UI线程上进行耗时操作,那样会造成界面卡顿,如下就是一个简单的示例: public partial class MainW ...

  6. java中的多线程——进度2

    package src;/*多线程总结:1,进程和线程的概念.    |--进程:    |--线程:2,jvm中的多线程体现.    |--主线程,垃圾回收线程,自定义线程.以及他们运行的代码的位置 ...

  7. Qt中的多线程编程

    http://www.ibm.com/developerworks/cn/linux/l-qt-mthrd/ Qt 作为一种基于 C++ 的跨平台 GUI 系统,能够提供给用户构造图形用户界面的强大功 ...

  8. 转:MFC中创建多线程

    MFC中创建多线程   MFC的多线程函数必须声明为静态的或者是全局函数(不同的在于全局函数不能访问类的私有静态成员,而静态类函数可以):但这样的线程函数只能访问静态的成员变量,要实现访问类的其他成员 ...

  9. C#中的多线程-入门

    概述与概念C#支持通过多线程并行地执行代码,一个线程有它独立的执行路径,能够与其它的线程同时地运行.一个C#程序开始于一个单线程,这个单线程是被CLR和操作系统(也称为“主线程”)自动创建的,并具有多 ...

随机推荐

  1. 决策树之 C4.5

    C4.5 是对 ID3 的一个优化,它依据信息增益率来进行属性选择. 关于决策树.请參见:http://blog.csdn.net/bone_ace/article/details/46299681 ...

  2. struts2获取ServletContext对象

      CreateTime--2017年9月7日09:24:40 Author:Marydon struts2获取ServletContext对象 需要导入: import javax.servlet. ...

  3. 在Mac上ppt导出pdf

    Step1:打开要操作的ppt,然后Command+P(print),出来打印的界面 Step2:在左下端选择Save as PDF就可以

  4. java equals与==区别

    java中的数据类型,可分为两类: 1.基本数据类型,也称原始数据类型.byte,short,char,int,long,float,double,boolean   他们之间的比较,应用双等号(== ...

  5. CentOS 5.5安装SVN(Subversion)

    检查已安装版本 #检查是否安装了低版本的SVN[root@localhost /]# rpm -qa subversion #卸载旧版本SVN[root@localhost modules]# yum ...

  6. mBot试用体验

    [Arduino话题] [mBot试用体验]1.mBot开箱体验(部分资料合集)http://bbs.elecfans.com/forum.php?mod=viewthread&tid=532 ...

  7. 2014年7月微软MVP名单揭晓!

    微软公司于2001年8月起開始在亚洲与各大基本的第三方站点上的微软技术相关论坛合作,微软称之为"亚洲社区支持"计划.    为了鼓舞大家在论坛中更好地互相帮助,共同提高,微软在全亚 ...

  8. OpenCV2马拉松第15圈——边缘检測(Laplace算子,LOG算子)

    收入囊中 拉普拉斯算子 LOG算子(高斯拉普拉斯算子) OpenCV Laplacian函数 构建自己的拉普拉斯算子 利用拉普拉斯算子进行图像的锐化 葵花宝典 在OpenCV2马拉松第14圈--边缘检 ...

  9. WebStorm 常用功能

    WebStorm 常用功能的使用技巧分享 WebStorm 是 JetBrain 公司开发的一款 JavaScript IDE,使用非常方便,可以使编写代码过程更加流畅. 本文在这里分享一些常用功能的 ...

  10. string去空格

    众所周知,string字符串去除空格的方法有trim()和replace(),区别在于trim()去首尾的空格,但是不能去中间的,而replace可以去除所有的空格. string data1=&qu ...