c# 线程锁的问题
现有一个类,类的主要功能是执行一个bat,并实时的将信息输出到richtextbox中,代码如下:
锁的目标是Run()在线程跑完后再给予返回值,所以加了个通知事件。(代码中的第一个地方)
但是调试过程中发现会卡在代码中第二个地方,形成死锁。
求问如何解决这个问题,谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Windows.Controls;
namespace WpfApplication1
{
public class RunBat
{
#region 私有变量
private StreamReader reader;
private StreamWriter writer;
private Process p;
private Thread t;
private object threadLock = new object();
FileInputInfo finfo = new FileInputInfo();
RichTextBox richTextBox1 = new RichTextBox();
AutoResetEvent resetEvent = new AutoResetEvent(false);
#endregion
public RunBat(string functionname,string file,string paras,string info,RichTextBox textBox)
{
finfo.filename = functionname + @"\" + file;
finfo.arg = paras;
finfo.info = info;
richTextBox1 = textBox;
}
public bool Run()
{
t = new Thread(new ParameterizedThreadStart(this.ExecuteCMD));
t.Start(finfo);
resetEvent.WaitOne();//这是第一个地方
return true;
}
private void ExecuteCMD(object finfo)
{
try
{
richTextBox1.Dispatcher.Invoke(new textBoxDelegate(AppendRichText), (finfo as FileInputInfo).info);//这是第二个地方
p = new Process();
p.StartInfo = new ProcessStartInfo();
p.StartInfo.FileName = (finfo as FileInputInfo).filename;
p.StartInfo.Arguments = (finfo as FileInputInfo).arg;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
reader = p.StandardOutput;
writer = p.StandardInput;
while (true)
{
if (reader.EndOfStream) { richTextBox1.Dispatcher.Invoke(new textBoxDelegate(AppendRichText), "\r\n"); break; }
string cmdoutput = reader.ReadLine();
richTextBox1.Dispatcher.Invoke(new textBoxDelegate(AppendRichText), cmdoutput);
}
}
catch
{ ;}
finally
{
resetEvent.Set();
t.Abort();
if (!p.HasExited) p.Kill();
}
}
delegate void textBoxDelegate(string message);
void AppendRichText(string message)
{
richTextBox1.AppendText(message + "\r\n");
richTextBox1.ScrollToEnd();
}
}
public class FileInputInfo
{
public string filename { get; set; }
public string arg { get; set; }
public string info { get; set;