嘿,我有这个测试后台工作者,似乎卡在DoWork方法上,或者RunWorkerCompleted可能没有被解雇,你们这些人看错了吗?
也许我没有正确实现这个:/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MailChimp;
using System.Threading;
using System.Runtime.InteropServices;
namespace Chimporter
{
public partial class Form1 : Form
{
//Worker thread flag set to false
static bool done = false;
//Console dll
[DllImport("Kernel32.dll")]
static extern Boolean AllocConsole();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void accountInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
//loadWindow pleaseWait = new loadWindow();
//pleaseWait.Show();
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(bg_DoWork);
bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
bg.RunWorkerAsync();
while (!done)
{
//Console.WriteLine("Waiting in Main, tid " + Thread.CurrentThread.ManagedThreadId);
//Thread.Sleep(100);
}
//AccountInfo accInfo = new AccountInfo();
//accInfo.Show();
}
public void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!AllocConsole())
{
Console.WriteLine("Fnished! " + Thread.CurrentThread.ManagedThreadId);
}
done = true;
}
public void bg_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 3; i++)
{
if (!AllocConsole())
{
Console.WriteLine("Work Line: " + i + ", tid " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
}
}
//string key = "e42713458882f6c2c27b3d6d951174a2-us6";
//var mc = new MCApi(key, true);
//string user = mc.GetAccountDetails().Username.ToString();
return;
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
//Exit application Form.Close()
Application.Exit();
}
}
}
答案 0 :(得分:2)
取出while (!done)
。它锁定主线程。在该线程上引发了worker complete事件,但由于它在循环中忙,所以它永远不会被引发。
RunWorkerCompleted事件的重点是,您可以在主线程上获得通知,而不必在繁忙的循环中将其锁定并使您的gui无响应。