如何使用后台工作者+进度条进行C#登录 [英] How to do a C# login using background worker + progress bar
问题描述
有人可以向我澄清背景工作者的实际工作方式。我想做一个简单的登录表单,它会在用户点击登录后显示登录进度,因为通常需要很长时间才能阅读登录详细信息,因此我想更新用户而不是让ui挂起。
我已经尝试了下面的代码,但我不知道如何或在哪里保存结果,以便我可以在登录成功或不成功时显示给用户。
我们非常感谢您的帮助。
我尝试过:
使用System;
使用System.Collections.Generic;使用System.ComponentModel
;
使用System.Data;使用System.Drawing
;
使用System.Linq;
使用System.Text;
使用System.Threading.Tasks;
使用System.Threading;
使用System.Windows.Forms;
使用System.Data.OleDb;
使用Excel = Microsoft.Office.Interop.Excel;
使用System.Runtime.InteropServices;
使用System.Drawing.Printing;
名称空间LoginDemo
{
公共部分类Form1:表格
{
公共Form1()
{
InitializeComponent();
}
//登录将被取消
private void btncancel_Click(object sender,EventArgs e)
{
if(backgroundWorker1.WorkerSupportsCancellation == true){
backgroundWorker1.CancelAsync();
btnlogin.Enabled = true;
btncancel.Enabled = false;
}
}
//登录将被处理
private void btnlogin_Click(object sender,EventArgs e)
{
testobj.username = txtid.Text.Trim()。ToString();
if(txtid.Text == string.Empty)
{
MessageBox.Show(Please enter username,Login Error,MessageBoxButtons.OK,MessageBoxIcon.Error);
txtid.Focus();
}
其他
{
lblMessage.Visible = true;
progressBar1.Visible = true;
testobj.ReadData();
backgroundWorker1.RunWorkerAsync();
btnlogin.Enabled = false;
btncancel.Enabled = true;
/ * if(chckrbm.Checked == true)
{
IMACBOX.Properties.Settings.Default.loginUsername = username;
IMACBOX.Properties.Settings.Default.Save();
} * /
// ReadData(connectionString);
}
}
//将处理繁重的工作
private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)
{
int dataload = 0;
for(dataload = 0; dataload< = 100; dataload ++)
{
if(backgroundWorker1.CancellationPending == true)
{
/ /用户点击取消按钮
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
休息;
}
else {
//做重工
// ReadDatas();
// dataload + = 1;
// testobj.ReadData();
backgroundWorker1.ReportProgress(dataload); //报告进度
}
}
e.Result = dataload;
}
//将在繁重的工作进度上更新进度条
private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e)
{
//更新程序进度条
progressBar1.Value = e.ProgressPercentage;
lblMessage.Text =Loading ...+ e.ProgressPercentage.ToString()+%;
}
//进度完成时会更新
private void backgroundWorker1_RunWorkerCompleted(对象发件人,RunWorkerCompletedEventArgs e)
{
//显示前检查进度消息
if(e.Cancelled == true)
{
MessageBox.Show(Operation Cancelled,Cancelled,MessageBoxButtons.OK,MessageBoxIcon.Information);
progressBar1.Value = 0; //如果用户取消了
lblMessage.Text =; //重置进度条值//清除标签
progressBar1.Visible = false;
}
else if(e.Error!= null)
{
// String somethingwrong = e.Result.ToString();
MessageBox.Show(e.Error +Error found+ e.Error.Message,Error,MessageBoxButtons.OK,MessageBoxIcon.Error);
progressBar1.Value = 0; //如果用户取消
lblMessage.Text =; //重置进度条值//清除标签
}
else {
MessageBox.Show(已完成进度+ e.Result.ToString()+,Done,MessageBoxButtons.OK,MessageBoxIcon.Information);
progressBar1.Value = 0; //如果用户取消了
lblMessage.Text =; //重置进度条值//清除标签
}
}
//执行繁重工作的方法
private void ReadDatas(){
try {
Thread.Sleep(100);
} catch(例外e){
MessageBox.Show(登录结果,e.Message,MessageBoxButtons.OK,MessageBoxIcon.Information);
progressBar1.Value = 0; //如果用户取消,则重置进度条值
lblMessage.Text =; //清除标签
}
}
private void Form1_Load(object sender,EventArgs e)
{
// username = txtid.Text.Trim();
// status = lblMessage.Text.ToString();
// bar = progressBar1.Value;
}
}
}
使用System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Threading.Tasks;
使用System.Threading;
使用System.Windows.Forms;
使用System.Data.OleDb;
使用Excel = Microsoft.Office.Interop.Excel;
使用System.Runtime.InteropServices;
使用System.Drawing.Printing;
使用System.Data;
命名空间LoginDemo
{
class testobj
{
public static String username,lastname,firstname,status,lblMessage;
public static int progressBar1Value = 0;
public static string connectionString = @Provider = Microsoft.ACE.OLEDB.12.0; Data Source = D:\IMAC\APP\IMACDB\FormDB2.xlsx; Extended Properties ='Excel 12.0; HDR =是;';
// public string connectionString = @Provider = Microsoft.ACE.OLEDB.12.0; Data Source = \\132.186.144.184\d $ \FormDB4.xlsx; Extended Properties ='Excel 12.0; HDR =是;';
// public string connectionString = @Provider = Microsoft.ACE.OLEDB.12.0; Data Source = \\132.186.144.239\d $ \IMAC\APP\IMACDB\FormDB2.xlsx ;扩展属性='Excel 12.0; HDR =是;';
public static OleDbConnection cnn;
public static OleDbCommand cmd;
public static OleDbDataAdapter da;
public static OleDbDataReader dr;
public DataSet dstResults = new DataSet();
public DataView myView;
public DataTable dtable;
public DataColumn c;
public static void ReadData()
{
try
{
string queryString =SELECT Employee_ID,LastName, FirstName FROM [Entries $] WHERE Employee_ID ='+ username.Trim()。ToString()+';
dr = null;
cnn = new OleDbConnection(connectionString);
cmd = new OleDbCommand(queryString,cnn);
cnn.Open();
dr = cmd.ExecuteReader();
if(dr.Read()== true)
{
线程。睡眠(100);
// MessageBox.Show(进度条);
firstname = dr [1] .ToString();
lastname = dr [2] .ToString();
MessageBox.Show(登录成功);
}
else
{
MessageBox.Show(Username Invalid,Error Message);
}
//完成阅读后始终致电关闭。
dr.Close();
}
//}
catch(例外e)
{
MessageBox.Show(Error+ e.Message,Error);
}
}
}
}
< blockquote> \FormDB4.xlsx;扩展属性='Excel 12.0; HDR =是;';
//公共字符串connectionString = @Provider = Microsoft.ACE.OLEDB.12.0;数据源= \\\ \\ 132.186.144.239 \d
\IMAC\APP \IMACDB \FormDB2.xlsx;扩展属性='Excel 12.0; HDR =是;';
public static OleDbConnection cnn;
public static OleDbCommand cmd;
public static OleDbDataAdapter da;
public static OleDbDataReader dr;
public DataSet dstResults = new DataSet();
public DataView myView;
public DataTable dtable;
public DataColumn c;
public static void ReadData()
{
try
{
string queryString =SELECT Employee _ID,LastName,FirstName FROM [条目
WHERE Employee_ID ='+ username.Trim()。ToString()+';
dr = null;
cnn = new OleDbConnection(connectionString);
cmd = new OleDbCommand(queryString,cnn);
cnn.Open();
dr = cmd.ExecuteReader();
if(dr.Read()== true)
{
线程。睡眠(100);
// MessageBox.Show(进度条);
firstname = dr [1] .ToString();
lastname = dr [2] .ToString();
MessageBox.Show(登录成功);
}
else
{
MessageBox.Show(Username Invalid,Error Message);
}
//完成阅读后始终致电关闭。
dr.Close();
}
//}
catch(例外e)
{
MessageBox.Show(Error+ e.Message,Error);
}
}
}
}
Hi,
Can someone please clarify to me how background worker actually works. I would like to do a simple login form that will show login progress to the user after they click loggin since normally it will take long to read login details therefore I would like to update the user instead of letting the ui hang.
I have tried the code below but I am not sure how or where do I save the result so that I can display to the user if login is successfull or not.
Any assistance will be much appreciated.
What I have tried:
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.Threading; using System.Windows.Forms; using System.Data.OleDb; using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; using System.Drawing.Printing; namespace LoginDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //Login will be cancelled private void btncancel_Click(object sender, EventArgs e) { if(backgroundWorker1.WorkerSupportsCancellation == true){ backgroundWorker1.CancelAsync(); btnlogin.Enabled = true; btncancel.Enabled = false; } } //Login will be processed private void btnlogin_Click(object sender, EventArgs e) { testobj.username = txtid.Text.Trim().ToString(); if (txtid.Text == string.Empty) { MessageBox.Show("Please enter username", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error); txtid.Focus(); } else { lblMessage.Visible = true; progressBar1.Visible = true; testobj.ReadData(); backgroundWorker1.RunWorkerAsync(); btnlogin.Enabled = false; btncancel.Enabled = true; /* if (chckrbm.Checked == true) { IMACBOX.Properties.Settings.Default.loginUsername = username; IMACBOX.Properties.Settings.Default.Save(); }*/ // ReadData(connectionString); } } // Will handle the heavy work private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { int dataload = 0; for (dataload = 0; dataload <= 100; dataload++) { if (backgroundWorker1.CancellationPending == true) { //user clicked cancel button e.Cancel = true; backgroundWorker1.ReportProgress(0); break; } else { //do the heavywork // ReadDatas(); // dataload += 1; // testobj.ReadData(); backgroundWorker1.ReportProgress(dataload);//Report progress } } e.Result = dataload; } // Will update progressbar on heavy work progress private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { //Updater progress bar progressBar1.Value = e.ProgressPercentage; lblMessage.Text = "Loading..." + e.ProgressPercentage.ToString() + " %"; } // Will update when progress is completed private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //Check progress before displaying message if (e.Cancelled == true) { MessageBox.Show("Operation Cancelled ", "Cancelled ", MessageBoxButtons.OK, MessageBoxIcon.Information); progressBar1.Value = 0; // Reset progressbar value if user cancelled lblMessage.Text = "";//clear the label progressBar1.Visible = false; } else if (e.Error != null) { // String somethingwrong = e.Result.ToString(); MessageBox.Show(e.Error + "Error found " + e.Error.Message , "Error ", MessageBoxButtons.OK, MessageBoxIcon.Error); progressBar1.Value = 0; // Reset progressbar value if user cancelled lblMessage.Text = "";//clear the label } else { MessageBox.Show("Progress done " + e.Result.ToString() + " ","Done ",MessageBoxButtons.OK,MessageBoxIcon.Information); progressBar1.Value = 0; // Reset progressbar value if user cancelled lblMessage.Text = "";//clear the label } } //Method for doing the heavy work private void ReadDatas() { try { Thread.Sleep(100); }catch(Exception e){ MessageBox.Show("Login Result ", e.Message , MessageBoxButtons.OK,MessageBoxIcon.Information); progressBar1.Value = 0; // Reset progressbar value if user cancelled lblMessage.Text = "";//clear the label } } private void Form1_Load(object sender, EventArgs e) { // username = txtid.Text.Trim(); // status = lblMessage.Text.ToString(); // bar = progressBar1.Value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Windows.Forms; using System.Data.OleDb; using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; using System.Drawing.Printing; using System.Data; namespace LoginDemo { class testobj { public static String username, lastname, firstname, status, lblMessage; public static int progressBar1Value = 0; public static string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\IMAC\APP\IMACDB\FormDB2.xlsx;Extended Properties='Excel 12.0;HDR=Yes;'"; // public string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\132.186.144.184\d$\FormDB4.xlsx;Extended Properties='Excel 12.0;HDR=Yes;'"; // public string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\132.186.144.239\d$\IMAC\APP\IMACDB\FormDB2.xlsx;Extended Properties='Excel 12.0;HDR=Yes;'"; public static OleDbConnection cnn; public static OleDbCommand cmd; public static OleDbDataAdapter da; public static OleDbDataReader dr; public DataSet dstResults = new DataSet(); public DataView myView; public DataTable dtable; public DataColumn c; public static void ReadData() { try { string queryString = "SELECT Employee_ID,LastName,FirstName FROM [Entries$] WHERE Employee_ID ='" + username.Trim().ToString() + "'"; dr = null; cnn = new OleDbConnection(connectionString); cmd = new OleDbCommand(queryString, cnn); cnn.Open(); dr = cmd.ExecuteReader(); if (dr.Read() == true) { Thread.Sleep(100); // MessageBox.Show("Progress bar"); firstname = dr[1].ToString(); lastname = dr[2].ToString(); MessageBox.Show("Login successfull"); } else { MessageBox.Show("Username Invalid", "Error Message"); } // Always call Close when done reading. dr.Close(); } // } catch (Exception e) { MessageBox.Show("Error " + e.Message, "Error"); } } } }
\FormDB4.xlsx;Extended Properties='Excel 12.0;HDR=Yes;'"; // public string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\132.186.144.239\d
\IMAC\APP\IMACDB\FormDB2.xlsx;Extended Properties='Excel 12.0;HDR=Yes;'"; public static OleDbConnection cnn; public static OleDbCommand cmd; public static OleDbDataAdapter da; public static OleDbDataReader dr; public DataSet dstResults = new DataSet(); public DataView myView; public DataTable dtable; public DataColumn c; public static void ReadData() { try { string queryString = "SELECT Employee_ID,LastName,FirstName FROM [Entries
WHERE Employee_ID ='" + username.Trim().ToString() + "'"; dr = null; cnn = new OleDbConnection(connectionString); cmd = new OleDbCommand(queryString, cnn); cnn.Open(); dr = cmd.ExecuteReader(); if (dr.Read() == true) { Thread.Sleep(100); // MessageBox.Show("Progress bar"); firstname = dr[1].ToString(); lastname = dr[2].ToString(); MessageBox.Show("Login successfull"); } else { MessageBox.Show("Username Invalid", "Error Message"); } // Always call Close when done reading. dr.Close(); } // } catch (Exception e) { MessageBox.Show("Error " + e.Message, "Error"); } } } }
这篇关于如何使用后台工作者+进度条进行C#登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!