winform使用多线程时,界面假死
主程序::
public bool ifFilter = true;
private Time _Timer;
private int _Interval = 86400000;
MySqlHelper db = new MySqlHelper();
FileStream fs;
public Filter()
{
InitializeComponent();
fs = new FileStream(@"log.txt", FileMode.OpenOrCreate);
}
private void button1_Click(object sender, EventArgs e)
{
ifFilter = false;
using (var db = new MySqlHelper())
{
BLL.Filter.FilterALL(db, fs);
}
ifFilter = true;
}
BLL下FilterALL方法:
static Dictionary<string, string> store = new Dictionary<string, string>();
internal static void FilterALL(MySqlHelper db, FileStream fs)
{
if (db == null) { }
db.ClearParameter();
string sqlStr = string.Format(@"SELECT id FROM nms_key_info;");
DataTable vs = db.GetDataSet(sqlStr).Tables[0];
int number= vs.Rows.Count;
ThreadPool.SetMaxThreads(1000,1000);
for (var i = 0; i < number; i++)
{
string idd = vs.Rows[i]["id"].ToString();
db.ClearParameter();
db.SetParameter("ids", MySql.Data.MySqlClient.MySqlDbType.VarChar, 32, vs.Rows[i]["id"].ToString());
string sqlstr = string.Format(@"SELECT allkeyword,refword,title,ly FROM nms_key_info where id=@ids");
string sqlstr2 = string.Format(@"SELECT content FROM nms_key_info_text where id=@ids");
DataTable str1 = db.GetDataSet(sqlstr).Tables[0];
string str2 = db.GetDataSet(sqlstr2).Tables[0].Rows[0]["content"].ToString();
pack mypack = new pack();
mypack.id = idd;
mypack.ly = str1.Rows[0]["ly"].ToString();
mypack.keywords = str1.Rows[0]["allkeyword"].ToString();
mypack.refwords = str1.Rows[0]["refword"].ToString();
mypack.title = str1.Rows[0]["title"].ToString();
mypack.cotent = str2;
ThreadPool.QueueUserWorkItem(new WaitCallback(run),mypack);
}
GetRecord(fs);
}
internal static void GetRecord(FileStream fs)
{
foreach(KeyValuePair<string,string> single in store)
{
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(single.Key + " " + single.Value+" "+DateTime.Now);
sw.Close();
}
}
internal static void run(object mypackage)
{
pack newpack = mypackage as pack;
bool ifcontent = true;
bool ifref = true;
for (int j = 0; j < newpack.keywords.ToString().Split('+').Length; j++)
{
if (newpack.title.IndexOf(newpack.keywords.ToString().Split('+')[j]) > -1 || newpack.cotent.IndexOf(newpack.keywords.ToString().Split('+')[j]) > -1)
{
ifcontent = true;
}
else
{
ifcontent = false;
}
}
if (ifcontent == false)
{
//StreamWriter sw = new StreamWriter(fs);
//sw.WriteLine(idd + " " + str1.Rows[0]["ly"]);
//sw.Close();
store.Add(newpack.id, newpack.ly);
System.Threading.Thread.CurrentThread.Abort();
}
else
{
for (int k = 0; k < newpack.refwords.ToString().Split('|').Length; k++)
{
if (newpack.title.IndexOf(newpack.refwords.ToString().Split('|')[k]) > -1 || newpack.cotent.IndexOf(newpack.refwords.ToString().Split('|')[k]) > -1)
{
ifref = true;
}
else
{
ifref = false;
}
}
if (ifref == false)
{
store.Add(newpack.id, newpack.ly);
System.Threading.Thread.CurrentThread.Abort();
}
}
}