用Task多线程操作C#T4生成代码,抛出System.ObjectDisposedException: 已关闭 Safe handle

9 篇文章 0 订阅

抛出的异常:
ErrorGeneratingOutput
D:\Work\wanghaoli.Kalman.Studio\Kalman.Studio\src\Kalman.Studio\bin\Debug\T4Template\whl实体2.tt(-1,-1) : error : An Exception was thrown while processing the template.
The following Exception was thrown:
System.ObjectDisposedException: 已关闭 Safe handle

如果是一般用单线程代码,不会导致异常,
抛出异常的代码:

//namespace Microsoft.VisualStudio.TextTemplating
//{
//
// 摘要:
//     Text templating engine
//public class Engine : ITextTemplatingEngine, IDebugTextTemplatingEngine
Engine engine = new Engine();
var outputContent = engine.ProcessTemplate(templateContent, host);

解决办法:
将Task改为Task task = new Task(action,object)处理

示例代码:

private void DoBuild()
{
	//完成计数
	System.Collections.Concurrent.ConcurrentBag<int> finished = new System.Collections.Concurrent.ConcurrentBag<int>();

	int total = listBox2.Items.Count;
	System.Collections.Concurrent.ConcurrentBag<Task> taskList = new System.Collections.Concurrent.ConcurrentBag<Task>();

	//模板文件内容
	string templateFile = gbTemplateFile.Text;
	string templateContent = File.ReadAllText(templateFile);

	//遍历选中的表,一张表对应生成一个代码文件
	foreach (object item in listBox2.Items)
	{
		/*
		 * 
		改成Task task = new Task(action,obj)处理解决下面的异常                
		 ErrorGeneratingOutput
D:\Work\wanghaoli.Kalman.Studio\Kalman.Studio\src\Kalman.Studio\bin\Debug\T4Template\whl实体2.tt(-1,-1) : error : An Exception was thrown while processing the template.  
The following Exception was thrown:
System.ObjectDisposedException: 已关闭 Safe handle

		#如果使用此代码:public static Task Run(Action action)将导致如上的异常
		 * 
		 */

		//多线程处理提高速度;        
		Task task = new Task(
			(g) =>
		{
			SOTable table = g as SOTable;
			string className = table.Name;
			if (cbDeleteTablePrifix.Checked) className = table.Name.RemovePrefix(tablePrefix, prefixLevel).Replace(" ", "");

			//类文件名帕斯卡命名
			if (cbClassNamePascal.Checked) className = className.InitialToUpperMulti();

			if (cbClassNameRemovePlural.Checked) className = className.EndsWith("s") ? className.TrimEnd('s') : className.Trim();
			if (cbAddSuffix.Checked) className = txtClassPrefix.Text.Trim() + className + txtClassSuffix.Text.Trim();

			List<SOColumn> columnList = table.ColumnList;//可能传入的是从PDObject对象转换过来的SODatabase对象
			if (columnList == null || columnList.Count == 0) columnList = DbSchemaHelper.Instance.CurrentSchema.GetTableColumnList(table);

			//生成代码文件
			TableHost host = new TableHost();
			host.Table = table;
			host.ColumnList = columnList;
			host.TemplateFile = templateFile;
			host.SetValue("NameSpace", nameSpace);
			host.SetValue("ClassName", className);
			host.SetValue("TablePrefix", tablePrefix);
			//host.SetValue("ColumnPrefix", columnPrefix);
			host.SetValue("PrefixLevel", prefixLevel);

			//模板引擎生成代码
			Engine engine = new Engine();
			var outputContent = engine.ProcessTemplate(templateContent, host);

			string outputFile = Path.Combine(outputPath, string.Format("{0}{1}", table.Name, host.FileExtention));
			if (cbClassNameIsFileName.Checked) outputFile = Path.Combine(outputPath, string.Format("{0}{1}", className, host.FileExtention));

			StringBuilder sb = new StringBuilder();
			if (host.ErrorCollection != null && host.ErrorCollection.HasErrors)
			{
				foreach (CompilerError err in host.ErrorCollection)
				{
					sb.AppendLine(err.ToString());
				}
				outputContent = outputContent + Environment.NewLine + sb.ToString();
				outputFile = outputFile + ".error";
			}

			if (Directory.Exists(outputPath) == false) Directory.CreateDirectory(outputPath);
			File.WriteAllText(outputFile, outputContent, Encoding.UTF8);

			//进度计算
			finished.Add(1);
			int percent = ConvertUtil.ToInt32(finished.Count * 100 / total, 0);
			backgroundWorker1.ReportProgress(percent, table);
		},
			item);
		task.Start();
		taskList.Add(task);

	}//end build code foreach

	Task.WaitAll(taskList.ToArray());
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王焜棟琦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值