我是这个领域的新宠。 我在我的Windows窗体中使用一个计时器,它以固定的间隔从数据库中获取数据。现在我希望我的计时器重新发送同样的信息,但我需要在屏幕上显示每秒运行的秒表。 有什么办法吗?代码在这里......
public partial class Form2 : Form
{
private Timer _timer;
int count = 0;
// The last time the timer was started
private DateTime _startTime = DateTime.MinValue;
// Time between now and when the timer was started last
private TimeSpan _currentElapsedTime = TimeSpan.Zero;
// Time between now and the first time timer was started after a reset
private TimeSpan _totalElapsedTime = TimeSpan.Zero;
// Whether or not the timer is currently running
private bool _timerRunning = false;
public Form2(String UserName)
{
InitializeComponent();
_timer = new Timer();
_timer.Interval = 1000;
_timer.Tick += new EventHandler(timer_Tick);
label4.Text = UserName;
}
private void richTextBox2_TextChanged(object sender, EventArgs e)
{
}
private void timer_Tick(object sender, EventArgs e)
{
count = count + 1;
var timeSinceStartTime = DateTime.Now - _startTime;
timeSinceStartTime = new TimeSpan(timeSinceStartTime.Hours,
timeSinceStartTime.Minutes,
timeSinceStartTime.Seconds);
// The current elapsed time is the time since the start button was
// clicked, plus the total time elapsed since the last reset
_currentElapsedTime = timeSinceStartTime + _totalElapsedTime;
// These are just two Label controls which display the current
// elapsed time and total elapsed time
label3.Text = timeSinceStartTime.ToString();
String str1, str2;
SqlDataReader rd1, rd2;
SqlConnection Con = new SqlConnection("Data Source=216.218.224.238;Database=chatapp;Uid=chatappuser;pwd=1234@ChatAppUser;MultipleActiveResultSets=true;");
// SqlConnection Con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Test;User ID=;Password=;Connection Timeout=600");
Con.Open();
rd1 = new SqlCommand("select top 1 Chat from chat where where email ='" + label4.Text + "'order by id Desc", Con).ExecuteReader();
rd1.Read();
str1 = rd1["Chat"].ToString();
rd1.Close();
rd2 = new SqlCommand("select top 1 UserInitial from chat where email ='" + label4.Text + "' order by id Desc", Con).ExecuteReader();
rd2.Read();
str2 = rd2["UserInitial"].ToString();
rd2.Close();
if (str1 != str2)
{
SqlDataReader rd3, rd4;
rd3 = new SqlCommand("select top 1 UserInitial from chat where email ='" + label4.Text + "'order by id desc", Con).ExecuteReader();
richTextBox1.Text = richTextBox1.Text + " <br /> " + rd3.Read();
rd3.Close();
rd4 = new SqlCommand("Update top 1 chat set Chat = UserInitial where email ='" + label4.Text + "'order by id desc", Con).ExecuteReader();
rd4.Read();
rd4.Close();
Con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (!_timerRunning)
{
// Set the start time to Now
_startTime = DateTime.Now;
// Store the total elapsed time so far
_totalElapsedTime = _currentElapsedTime;
_timer.Start();
_timerRunning = true;
}
else // If the timer is already running
{
_timer.Stop();
_timerRunning = false;
}
SqlDataReader rd5;
SqlConnection Con = new SqlConnection("Data Source=216.218.224.238;Database=chatapp;Uid=chatappuser;pwd=1234@ChatAppUser;MultipleActiveResultSets=true;");
// SqlConnection Con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Test;User ID=;Password=;Connection Timeout=600");
Con.Open();
richTextBox1.Text = richTextBox1.Text + "<br />Me:" + richTextBox2.Text;
rd5 = new SqlCommand("Update chat set UserInitial ='" + richTextBox2.Text + "' order by id Desc where email ='" + label4.Text + "'", Con).ExecuteReader();
rd5.Read();
rd5.Close();
Con.Close();
}
private void button3_Click(object sender, EventArgs e)
{
_timer.Stop();
_timerRunning = false;
// Reset the elapsed time TimeSpan objects
_totalElapsedTime = TimeSpan.Zero;
_currentElapsedTime = TimeSpan.Zero;
label3.Text = _totalElapsedTime.ToString();
MessageBox.Show(count.ToString());
count = 0;
}
先谢谢.....
答案 0 :(得分:5)
您可以使用StopWatch课程获得时间Elapsed
来自MSDN:
提供一组可用于的方法和属性 准确地测量经过的时间。
第1步:创建StopWatch
变量作为类级变量。
步骤2:只要您想开始计算,就会调用Start()
方法。
第3步:对于每个timer_tick
事件,您可以使用usig stopwatch.Elapsed.Seconds
经过的Totalseconds。
试试这个:
Stopwatch watch = new Stopwatch();
watch.Start();
private void timer_Tick(object sender, EventArgs e)
{
label1.Text = watch.Elapsed.Seconds.ToString();
}
答案 1 :(得分:1)
您可以使用BackgroundWorker。
在OnDoWork事件中,您可以添加逻辑以从数据库中获取数据,并在每个固定的时间间隔内更新您的界面。 您可以启动和停止,请在链接中获取有关如何使用它的更多详细信息。
修改强>
我制作了一个小型演示来演示后台工作者的使用。无论如何,您应该改进从数据库中检索数据的逻辑。 注意:根据您的查询运行速度,如果它们很慢,您应该在不同的线程上执行此操作,检索数据并显示秒表,否则您的秒表值将是错误的。
private bool _running;
private BackgroundWorker _bw;
private Stopwatch _watch;
private System.Timers.Timer _timer;
public Form1()
{
InitializeComponent();
}
private void BwOnProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void BwOnDoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (_running)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
return;
}
else
{
// Perform a time consuming operation and report progress.
String str1, str2;
SqlDataReader rd1, rd2;
SqlConnection Con =
new SqlConnection(
"Data Source=216.218.224.238;Database=chatapp;Uid=chatappuser;pwd=1234@ChatAppUser;MultipleActiveResultSets=true;");
// SqlConnection Con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Test;User ID=;Password=;Connection Timeout=600");
Con.Open();
rd1 =
new SqlCommand(
"select top 1 Chat from chat where where email ='" + label4.Text + "'order by id Desc", Con)
.ExecuteReader();
rd1.Read();
str1 = rd1["Chat"].ToString();
rd1.Close();
rd2 =
new SqlCommand(
"select top 1 UserInitial from chat where email ='" + label4.Text + "' order by id Desc",
Con)
.ExecuteReader();
rd2.Read();
str2 = rd2["UserInitial"].ToString();
rd2.Close();
if (str1 != str2)
{
SqlDataReader rd3, rd4;
rd3 =
new SqlCommand(
"select top 1 UserInitial from chat where email ='" + label4.Text + "'order by id desc",
Con).ExecuteReader();
var value = rd3.Read();
rd3.Close();
if (richTextBox1.InvokeRequired)
{
richTextBox1.BeginInvoke(
new MethodInvoker(() => richTextBox1.Text += richTextBox1.Text + " <br /> " + value));
}
else
{
richTextBox1.Text = richTextBox1.Text + " <br /> " + value;
}
rd4 =
new SqlCommand(
"Update top 1 chat set Chat = UserInitial where email ='" + label4.Text +
"'order by id desc", Con).ExecuteReader();
rd4.Read();
rd4.Close();
Con.Close();
}
Thread.Sleep(1000); //sleep 1 second
}
//System.Threading.Thread.Sleep(500);
}
}
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (label3.InvokeRequired)
{
label3.BeginInvoke(new MethodInvoker(() => label3.Text = _watch.Elapsed.Seconds.ToString()));
}
else
{
label3.Text = _watch.Elapsed.Seconds.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
_running = true;
_watch = new Stopwatch();
_watch.Start();
_bw.RunWorkerAsync();
//start the timer
_timer.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
_bw = new BackgroundWorker();
_bw.WorkerReportsProgress = true;
_bw.DoWork += BwOnDoWork;
_bw.ProgressChanged += BwOnProgressChanged;
// instantiate the timer
_timer = new System.Timers.Timer();
_timer.Interval = 1000;
_timer.Elapsed += _timer_Elapsed;
}
private void button2_Click(object sender, EventArgs e)
{
_running = false;
_bw.CancelAsync();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//dispose resources
_bw.CancelAsync();
_bw.Dispose();
_watch.Stop();
_timer.Dispose();
}
要删除Thread.Sleep(1000)
,您可以将计时器仅用于表单线程上的秒表,并将更新聊天工作分配给后台工作人员。这样,经过的时间会更准确。