所以我在C#程序上遇到“检测到DisconectedContext”错误。这是我第一次与背景工作者合作,现在我对他们了解不多。所以这是与该问题相关的部分:
private void bt_crack_Click(object sender, EventArgs e)
{
if (isWorkbookProtected())
{
MessageBox.Show("Tem password");
if (!worker.IsBusy)
{
worker.RunWorkerAsync();
}
}
else
{
MessageBox.Show("Não tem password");
}
}
private bool isWorkbookProtected()
{
try
{
workbook.Unprotect(string.Empty);
return false;
}
catch (Exception e)
{
return true;
}
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
Builder str = new StringBuilder();
while (!worker.CancellationPending)
{
str.next();
worker.ReportProgress(str.getCounter(), str.getCurrent());
}
e.Cancel = true;
}
private void bt_stop_Click(object sender, EventArgs e)
{
worker.CancelAsync();
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lb_string.Text = e.UserState as String;
lb_attempts.Text = e.ProgressPercentage.ToString();
}
private void bt_exit_Click(object sender, EventArgs e)
{
System.Windows.Forms.Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Complete!");
}
这是Builder界面:
public interface Builder
{
string next();
string getCurrent();
int getCounter();
}
StringBuilder继续无限地构建一个String。 那么,任何人都能解释一下这里发生了什么吗?
先谢谢。
编辑:这是我的StringBuilder类:
public class StringBuilder : Builder
{
private Char[] current;
private int counter;
public const int MAX = 255;
public const int MIN = 0;
public StringBuilder()
{
counter = 0;
char[] c = new char[1];
c[0] = (char)MIN;
current = c;
}
public string next()
{
current = buildNextString();
counter++;
return current.ToString();
}
public string getCurrent()
{
return current.ToString();
}
public int getCounter()
{
return counter;
}
private Char[] buildNextString()
{
Char[] c = current;
c = checkChar(c, c.Length);
return c;
}
private Char[] checkChar(Char[] c, int num)
{
if (num > 1)
{
if ((int)c[num - 1] == MAX)
{
c[num - 1] = (char)MIN;
c[num - 2]++;
c = checkChar(c, num - 1);
}
else
{
c[num - 1]++;
}
}
else if (num == 1)
{
if ((int)c[num - 1] == MAX)
{
c[num - 1] = (char)MIN;
c = addChar(c);
}
else
{
c[num - 1]++;
}
}
return c;
}
private Char[] addChar(Char[] c)
{
Char[] n = new Char[c.Length + 1];
n[0] = (char)Char.MinValue;
for (int i = 0; i < c.Length; i++)
{
n[i + 1] = c[i];
}
return n;
}
}