C# Variable won't update - c#

I'm writing a C# Program to display the Temperature of CPU/GPU from my PS3.
There is a connect button. This works really good and it shows me the Temp. from my PS3's CPU/GPU.
Now I've implemented a "refresh" button, which starts a timer for all x Seconds to do this:
public void get_psdata()
{
//Get data from PS3
cputemp = PS3.GetTemperatureCELL();
gputemp = PS3.GetTemperatureRSX();
psversion = PS3.GetFirmwareVersion();
psversiontype = PS3.GetFirmwareType();
//Set data into Var
L_cputemp_show.Text = cputemp;
L_gputemp_show.Text = gputemp;
L_firmware_show.Text = psversion;
L_type_show.Text = psversiontype;
//Update Label
L_cputemp_show.Refresh();
}
So this "get_psdata" works only on the first time, when i press the connect button. (The connect button starts directly the "get_psdate" function, while the refresh button does a bit different, like you can see later...)
Here is the code to run the get_psdata:
//B_connect, Connect Button
private void b_connect_Click(object sender, EventArgs e)
{
//Connect CCAPI to PS3 if Button clicked
PS3.ConnectTarget(psip);
//Check Connection
if (PS3.SUCCESS(PS3.ConnectTarget(psip)))
{
//Show Status
MessageBox.Show("Connected to: " + psip + "!");
this.L_status_show.Text = "Connected!"; L_status_show.ForeColor = System.Drawing.Color.Green;
//Call Function
get_psdata();
}
else
{
//Show Status
MessageBox.Show("Failed to Connect to: " + psip + "!");
this.L_status_show.Text = "Not Connected!"; L_status_show.ForeColor = System.Drawing.Color.Red;
}
}
For testing, I added a Messagebox.Show to the "get_psdata" function to see if it runs all x Seconds... Yes it does and this is my timer:
//Function to set refresh delay
public void refresh_delay()
{
MessageBox.Show("Delay set to " + refresh_int + " Seconds!");
refresh_int = refresh_int * 1000; //Change to Miliseconds
init_timer();
}
//Timer
public Timer timer1;
public void init_timer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = refresh_int; // in miliseconds
timer1.Start();
}
public void timer1_Tick(object sender, EventArgs e)
{
get_psdata();
}
And this is what starts my timer:
//B_set, Set refresh time button
private void B_set_Click(object sender, EventArgs e)
{
//Check refresh Value
refresh_string = TB_refresh.Text;
//Check empty
if (refresh_string != "")
{
//Check minimum
refresh_int = Convert.ToInt32(TB_refresh.Text);
if (refresh_int < 5)
{
DialogResult confirm = MessageBox.Show("This is not the delay you are looking for! \r (I recommend to set it bigger then 5) \r Continue with " + refresh_int + " Seconds?", "Realy dude?", MessageBoxButtons.YesNo);
if (confirm == DialogResult.Yes)
{
//Call Function
refresh_delay();
}
}
else
{
//Call Function
refresh_delay();
}
}
else
{
MessageBox.Show("Please set refresh delay!");
}
}
So I'm sure that the code will run all x Seconds but the label's are only updated when I hit the connect button, but not if I start the counter after connecting with the B_set button.
The Variables from "get_psdata" are not showing the updated value. They just show the result from the first "Get". Why aren't they show the latest result?

If I use your code in a fresh winforms screen, all works well. I did however use the following implementation for get_psdata.
public void get_psdata()
{
var rnd = new Random();
//Set data into Var
L_cputemp_show.Text = rnd.Next().ToString();
L_gputemp_show.Text = rnd.Next().ToString();
L_firmware_show.Text = rnd.Next().ToString();
L_type_show.Text = rnd.Next().ToString();
//Update Label
L_cputemp_show.Refresh();
}
With an interval of 1 second, this gives me new values on screen every second. Could you try this code please?
If this works well, then the problem is with the PS3 object that doesn't refresh its internals perhaps?

Related

No row at position (-1) - SQL Server when trying to save DataTable changes

I have a Windows Forms data entry applet for entering data into a small SQL Server database. I keep seeing this error when trying to save my new record after clicking AddNewItem button on the binding navigator component.
My code on clicking the save button on the binding navigator looks like this:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
this.Validate();
int currentPosition = this.witsStatusDBDataSet.TestCase.Rows.Count - 1;
WitsStatusDBDataSet.TestCaseRow row = (WitsStatusDBDataSet.TestCaseRow)witsStatusDBDataSet.TestCase.Rows[currentPosition];
row.AcceptChanges();
witsStatusDBDataSet.TestCase.AcceptChanges();
this.testCaseBindingSource.EndEdit();
int current = witsStatusDBDataSet.TestCase.Rows.Count - 1;
testCaseTableAdapter.Update(this.witsStatusDBDataSet.TestCase.Rows[current]);
WitsStatusDBEntry.WitsStatusDBDataSetTableAdapters.TableAdapterManager manager = new TableAdapterManager();
manager.UpdateAll(witsStatusDBDataSet);
SysTimer = new System.Timers.Timer(2500);
statusLabel1.Text = "Updated successfully.";
SysTimer.Start();
}
catch(Exception exc)
{
string msg = exc.Message + " : " + exc.StackTrace;
Clipboard.SetText(msg);
MessageBox.Show(msg);
}
}
If I enter the data manually in SQL Server Mgmt Studio, the binding navigator successfully loads it and I can use Move Next and Move Previous successfully.
But if I have a brand-new database that has just been deployed, with no records, I get this error.
I checked StackOverflow for similar issues, but nothing seemed to be the same situation.
I re-coded the method, based on mason's comment. Here is the working code:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
WitsStatusDBDataSet.TestCaseRow row = null;
this.Validate();
int currentPosition = this.witsStatusDBDataSet.TestCase.Rows.Count - 1;
if(currentPosition == -1)
{
row = AddRowToDataTable(testCase: witsStatusDBDataSet.TestCase);
}
if (row == null)
{
currentPosition = this.witsStatusDBDataSet.TestCase.Rows.Count - 1;
}
row.AcceptChanges();
witsStatusDBDataSet.TestCase.AcceptChanges();
this.testCaseBindingSource.EndEdit();
testCaseTableAdapter.Update(row);
testCaseTableAdapter.InsertCase(row.Title, row.IsAutomated, row.Description, row.State, row.Area, row.Iteration, row.Priority,
row.Severity, row.Owner, row.CreatedDate, row.ModifiedDate, row.TFS_Case_ID, row.TFSInstance);
WitsStatusDBEntry.WitsStatusDBDataSetTableAdapters.TableAdapterManager manager = new TableAdapterManager();
manager.Connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=WitsStatusDB;Integrated Security=True");
manager.UpdateAll(witsStatusDBDataSet);
SysTimer = new System.Timers.Timer(2500);
statusLabel1.Text = "Updated successfully.";
SysTimer.Start();
}
catch(Exception exc)
{
string msg = exc.Message + " : " + exc.StackTrace;
Clipboard.SetText(msg);
MessageBox.Show(msg);
}
}
Notice I had to call "AddRowToDataDable()" - that method simply transfers the contents of the Windows Form to the TestCaseRow object.

Power source connected event UWP

I am working on a UWP application in C#.
We have a requirement to perform an operation whenever device is connected to power source for charging. We need to sense that event and do our tasks which are dependent on it.
So far I have found this which raises event when 1% charging is decreased
but we are interested in device connected to power source event.
I got one example where event is binded when page loads.
Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated;
and get the report as below.
private void GetBatteryReport(object sender, RoutedEventArgs e)
{
// Clear UI
BatteryReportPanel.Children.Clear();
if (AggregateButton.IsChecked == true)
{
// Request aggregate battery report
RequestAggregateBatteryReport();
}
else
{
// Request individual battery report
RequestIndividualBatteryReports();
}
// Note request
reportRequested = true;
}
This is not what I require.
Can anyone please guide me how to sense device power source connected event?
PowerManager.PowerSupplyStatus can be Adequate, InAdequate, or NotPresent:
var pss = PowerManager.PowerSupplyStatus;
if (pss.ToString() == "NotPresent")
{
pluggedin = false;
} else {
pluggedin = true;
}
Try this to get the battery status:
private void OnPageLoad(object sender, RoutedEventArgs e)
{
PowerManager.BatteryStatusChanged += OnBatteryStatusChanged;
}
private async void OnBatteryStatusChanged(object sender, object e)
{
var bs = PowerManager.BatteryStatus;
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var dischargeTime = PowerManager.RemainingDischargeTime;
this.batteryProgress.Value = PowerManager.RemainingChargePercent;
this.batteryProgressPercentage.Text = PowerManager.RemainingChargePercent + " % remaining";
this.batteryStatus.Text = "Battery Level: " + bs;
this.batteryDischargeTime.Text = "Battery Left: " + dischargeTime.Hours + " hours " + dischargeTime.Minutes + " minutes " + dischargeTime.Seconds + " seconds";
});
}

How to stop timer affacted by button click?

i am working on a winform application in which i have a timer.it is being used for showing stopwatch on the form. When i fire a button than my timer is interrupted. i want my timer to be uninterrupted while button is clicked. My code is as followed:-
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;
}
SqlConnection Con = new SqlConnection("Data Source=69.162.83.242,1232;Initial Catalog=test1;Uid=test;pwd=1234#Test;MultipleActiveResultSets=true;Connect TimeOut=60000;");
//SqlConnection Con = new SqlConnection("Data Source=ADMIN-PC\\YASH;Initial Catalog=test;Integrated Security=True; Connect TimeOut=600");
Con.Open();
string messageMask = "{0} # {1} : {2}";
string message = string.Format(messageMask, label6.Text, DateTime.Now.ToShortTimeString(), richTextBox2.Text);
richTextBox1.AppendText(Environment.NewLine + message);
SqlCommand cmd, cmd1;
cmd = new SqlCommand("Update Chat set UserInitial=#message,Updated=1 where ExpertName ='" + label6.Text + "'", Con);
cmd.Parameters.AddWithValue("#message", message);
cmd.ExecuteNonQuery();
Con.Close();
richTextBox2.Text = String.Empty;
richTextBox1.ScrollToCaret();
}
private void timer1_Tick(object sender, EventArgs e)
{
richTextBox1.ScrollToCaret();
count = count + 1;
count1 = count1 + 1;
timerSinceStartTime = new TimeSpan(timerSinceStartTime.Hours, timerSinceStartTime.Minutes, timerSinceStartTime.Seconds + 1);
// The current elapsed time is the time since the start button was
// clicked, plus the total time elapsed since the last reset
_currentElapsedTime = timerSinceStartTime + _totalElapsedTime;
// These are just two Label controls which display the current
// elapsed time and total elapsed time
if (count1 == 180)
{
MessageBox.Show("You are Automaticlly hired by User");
if (label7.Visible == true)
{
label7.Visible = false;
count = 0;
timerSinceStartTime = new TimeSpan(00, 00, 00);
label3.Visible = true;
}
}
label3.Text = timerSinceStartTime.ToString();
// If we're running on the UI thread, we'll get here, and can safely update
// the label's text.
richTextBox1.ScrollToCaret();
}
how to solve it??
thanks in Advance
Your problem stems from the fact you're using System.Windows.Forms.Timer which is not threaded and relies on the message pump. While your program is busy in the UI thread the message pump won't be processed.
You can improve this by moving to a timer that supports threads. I prefer System.Timers.Timer but there's also System.Threading.Timer.
With System.Timers.Timer the tick event is raised on a background thread if you don't pass any sync object in so that any code within the event handler will be handled in a separate thread.
Of course, to update the form we have to marshal back to the UI thread so we'll also need to use Control.Invoke().
This is very rough, but something like this:
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(OnTimer);
timer.Interval = 1000;
timer.AutoReset = false;
timer.Enabled = true;
public void OnTimer(object sender, ElapsedEventArgs e)
{
// Do something busy like dancing
// Update form
Invoke((MethodInvoker)delegate() {
UpdateForm();
});
// Restart timer
((System.Timers.Timer)sender).Start();
}
public void UpdateForm()
{
// Code to update the form
}
Note I use AutoReset = false so that if the tick event takes longer than the timer interval you won't get overlap. You may or may not want this it entirely depends on what you're doing.
You can try this,
private bool bStopTimer = true;
private void StartTimer()
{
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.ThreadTimer));
thread.IsBackground = true;
thread.Start();
}
private void ThreadTimer()
{
while (bStopTimer)
{
System.Threading.Thread.Sleep(1000); //interval in millisecond
lock(lblLabel.Text)
{
lblLable.Text = System.DateTime.Now.ToString("HH:mm:ss");
}
}
}
Update
place this line before Application.Run(new frmForm);
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

Sample my class properties every few seconds

my class start new process (Tshark) and start capturing, from the main form i am checking the class properties in order to update my GUI, sometimes the received packets rate i so high that my GUI stuck so i want the option to check whose properties every 1-2 second.
this is my progress change function who checking my class all the time and in this point i am update my GUi, how can i checking those properties every 2 seconds ?
Tshark tshark = new Tshark();
private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tshark = e.UserState as Tshark;
lblNumberOfReceivedPackets.Text = tshark._receivesPackets.ToString("#,##0");
lblTrafficRate.Text = (tshark._bitsPerSecond * 0.000001).ToString("0.##") + " Mbit/sec" + " (" + tshark._bitsPerSecond.ToString("#,##0") + " Bits/sec" + ")";
lblPacketsRate.Text = tshark._packetsPerSecond.ToString("#,##0") + " Packets/sec";
lblStatus.Text = tshark._status;
lblFileSize.Text = formatBytes(tshark._myFile.Length);
tshark._myFile.Refresh();
}
Check if 2 seconds has passed since the last check. Here, I'm using a class member to tract that time.
private DateTime _LastCheck = DateTime.MinValue;
private private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (_LastCheck.AddSeconds(2) <= DateTime.Now)
{
_LastCheck = DateTime.Now;
// do the UI update.
}
}
Instead of updating the UI within the BackgroundWorker you can just create a Timer to do the job
private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tshark = e.UserState as Tshark;
}
In the ctor create the timer:
_timer = new Timer()
_timer.Intrerval = 2000;
_timer.Tick += UpdateUI;
_timer.Start();
You can add some checking in case the values have changed so you don't update the UI needlessly:
private void UpdateUI()
{
var local = _tshark;
if(local != null)
{
lblNumberOfReceivedPackets.Text = local._receivesPackets.ToString("#,##0");
lblTrafficRate.Text = (local._bitsPerSecond * 0.000001).ToString("0.##") + " Mbit/sec" + " (" + local._bitsPerSecond.ToString("#,##0") + " Bits/sec" + ")";
lblPacketsRate.Text = local._packetsPerSecond.ToString("#,##0") + " Packets/sec";
lblStatus.Text = local._status;
lblFileSize.Text = formatBytes(local._myFile.Length);
local._myFile.Refresh();
}
}

WinForm Timers Access Textbox

So I am trying to create a basic WinForm Application that uses SNMP, from snmpsharpnet.
I have two buttons 'Eye' and 'Jitter' that when one is pressed a timer starts which executes SNMP code inside the timer handler every minute.
I am trying to write the SNMP output to a textbox from the timer handler but everything I try either leads to thread exceptions or a continuous running process when I exit the program.
I have tried so many different things to fix those two errors that I may be screwing everything up but here is the code I have:
using System;
using System.Net;
using SnmpSharpNet;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public static bool stop = false;
static bool min = false, sec = false, eye = false, jitter = false;
static string ipAdd = "";
static System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
static int alarmCounter = 1;
static bool exitFlag = false;
static TextBox textbox;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textbox = outputBox;
}
private void IPtext_TextChanged(object sender, EventArgs e)
{
ipAdd = IPtext.Text;
}
private void stopButton_Click(object sender, EventArgs e)
{
stop = true;
timer.Stop();
}
// This is the method to run when the timer is raised.
private static void TimerEventProcessor(Object myObject,
EventArgs myEventArgs)
{
timer.Stop();
// If stop button has not been pressed then continue timer.
if (stop == false)
{
textbox.Clear();
// Restarts the timer and increments the counter.
alarmCounter += 1;
timer.Enabled = true;
/*
textbox.Invoke(
new MethodInvoker(
delegate { textbox.AppendText("fsjdaò"); }));
*/
System.IO.StreamWriter file;
if (eye == true)
{
file = new System.IO.StreamWriter("c:/Users/bshellnut/Desktop/Eye.txt", true);
}
else
{
file = new System.IO.StreamWriter("c:/Users/bshellnut/Desktop/Jitter.txt", true);
}
// SNMP community name
OctetString community = new OctetString("public");
// Define agent parameters class
AgentParameters param = new AgentParameters(community);
// Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
param.Version = SnmpVersion.Ver2;
// Construct the agent address object
// IpAddress class is easy to use here because
// it will try to resolve constructor parameter if it doesn't
// parse to an IP address
IpAddress agent = new IpAddress(ipAdd);
// Construct target
UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
// Define Oid that is the root of the MIB
// tree you wish to retrieve
Oid rootOid;
if (eye == true)
{
rootOid = new Oid("1.3.6.1.4.1.128.5.2.10.14"); // ifDescr
}
else
{
rootOid = new Oid("1.3.6.1.4.1.128.5.2.10.15");
}
// This Oid represents last Oid returned by
// the SNMP agent
Oid lastOid = (Oid)rootOid.Clone();
// Pdu class used for all requests
Pdu pdu = new Pdu(PduType.GetBulk);
// In this example, set NonRepeaters value to 0
pdu.NonRepeaters = 0;
// MaxRepetitions tells the agent how many Oid/Value pairs to return
// in the response.
pdu.MaxRepetitions = 5;
// Loop through results
while (lastOid != null)
{
// When Pdu class is first constructed, RequestId is set to 0
// and during encoding id will be set to the random value
// for subsequent requests, id will be set to a value that
// needs to be incremented to have unique request ids for each
// packet
if (pdu.RequestId != 0)
{
pdu.RequestId += 1;
}
// Clear Oids from the Pdu class.
pdu.VbList.Clear();
// Initialize request PDU with the last retrieved Oid
pdu.VbList.Add(lastOid);
// Make SNMP request
SnmpV2Packet result;
try
{
result = (SnmpV2Packet)target.Request(pdu, param);
//textbox.Text = "";
}
catch (SnmpSharpNet.SnmpException)
{
textbox.Invoke(
new MethodInvoker(
delegate { textbox.AppendText("Could not connect to the IP Provided."); }));
timer.Stop();
//outputBox.Text += "Could not connect to the IP Provided.";
break;
}
// You should catch exceptions in the Request if using in real application.
// If result is null then agent didn't reply or we couldn't parse the reply.
if (result != null)
{
// ErrorStatus other then 0 is an error returned by
// the Agent - see SnmpConstants for error definitions
if (result.Pdu.ErrorStatus != 0)
{
// agent reported an error with the request
/*Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
result.Pdu.ErrorStatus,
result.Pdu.ErrorIndex);*/
textbox.Invoke(
new MethodInvoker(
delegate { textbox.AppendText("Error in SNMP reply. " + "Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex); }));
//outputBox.Text = "Error in SNMP reply. " + "Error " + result.Pdu.ErrorStatus + " index " + result.Pdu.ErrorIndex;
lastOid = null;
break;
}
else
{
// Walk through returned variable bindings
foreach (Vb v in result.Pdu.VbList)
{
// Check that retrieved Oid is "child" of the root OID
if (rootOid.IsRootOf(v.Oid))
{
/*Console.WriteLine("{0} ({1}): {2}",
v.Oid.ToString(),
SnmpConstants.GetTypeName(v.Value.Type),
v.Value.ToString());*/
textbox.Invoke(
new MethodInvoker(
delegate { textbox.AppendText(v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) +
" " + v.Value.ToString() + Environment.NewLine); }));
//outputBox.Text += v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) +
//" " + v.Value.ToString() + Environment.NewLine;
file.WriteLine(v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) +
" " + v.Value.ToString(), true);
if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
lastOid = null;
else
lastOid = v.Oid;
}
else
{
// we have reached the end of the requested
// MIB tree. Set lastOid to null and exit loop
lastOid = null;
}
}
}
}
else
{
//Console.WriteLine("No response received from SNMP agent.");
textbox.Invoke(
new MethodInvoker(
delegate { textbox.AppendText("No response received from SNMP agent."); }));
//outputBox.Text = "No response received from SNMP agent.";
}
}
target.Close();
file.Close();
}
else
{
// Stops the timer.
exitFlag = true;
}
}
private void eyeButton_Click(object sender, EventArgs e)
{
outputBox.Text = "Connecting...";
eye = true;
jitter = false;
stop = false;
timer.Tick += new EventHandler(TimerEventProcessor);
// Sets the timer interval to 5 seconds.
timer.Interval = 5000;
timer.Start();
// Runs the timer, and raises the event.
while (exitFlag == false)
{
// Processes all the events in the queue.
Application.DoEvents();
}
}
private void jitterButton_Click(object sender, EventArgs e)
{
outputBox.Text = "Connecting...";
eye = false;
jitter = true;
stop = false;
timer.Tick += new EventHandler(TimerEventProcessor);
// Sets the timer interval to 5 seconds.
timer.Interval = 5000;
timer.Start();
// Runs the timer, and raises the event.
while (exitFlag == false)
{
// Processes all the events in the queue.
Application.DoEvents();
}
}
private void Seconds_CheckedChanged(object sender, EventArgs e)
{
min = false;
sec = true;
}
private void Minutes_CheckedChanged(object sender, EventArgs e)
{
min = true;
sec = false;
}
}
}
I believe you are running into a deadlock on the UI thread.
TimerEventProcessor() is called by your instance of System.Windows.Forms.Timer, which runs on the UI thread. When the timer goes off, I believe it puts a message into the UI thread's message queue to call your TimerEventProcessor() method. That method in turn calls textbox.Invoke(), which puts another message into the queue and then waits for it to be processed.
Your UI thread is now stuck, as it is in the middle of processing a message, but must wait until another message is processed before it can continue. The calls to Application.DoEvents() do you no good, as they are not being called once your program enters TimerEventProcessor(). (They're also unnecessary, since your button click handlers wouldn't be blocking the UI thread anyway.)
Since the timer runs on the UI thread, you can get rid of the textbox.Invoke() calls and just access textbox directly.
Summary:
Replace your calls to textbox.Invoke() with direct access to textbox
Remove your calls to Application.DoEvents()
Note: if you got the Application.DoEvents() logic from the MSDN example for using a timer, they put it there so that the application doesn't quit once the Main function completes.
Update: You can see if this is truly the issue by replacing your calls to textbox.Invoke with the following code. If this code works, then you definitely have a UI message queue deadlocking issue. Also, if this does resolve the issue, I would not recommend keeping this as the solution, but rather, addressing the deadlocking as suggested above.
// Make the request asynchronously
System.IAsyncResult asyncResult = textbox.BeginInvoke(
new MethodInvoker(
delegate { /* insert delegate code here */ }));
// Process the message queue until this request has been completed
while(!asyncResult.IsCompleted) Application.DoEvents();
// Clean up our async request
textbox.EndInvoke(asyncResult);
Since you seem to have your code working, you can ignore the above test code.
Your problem is not related to the timer and all the Invoke statements you use are not necessary. The System.Windows.Forms.Timer class operates in the UI thread. Look here: http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

Categories

Resources