c# chat window application problem with timer
I'm developing a chat application. For getting frequetly comming request,messages and zone request I'm using one timer and call all methods on timer.now. The problem is that when ever I click on any control in the application this gives me a late resp开发者_如何学Pythononse due to the timer running. It first hangs until it completes the timer code then control click event is fire.
So, any help on how to handle this is appreciated, I also tried threading but this didn't help.
Please give me any idea if u have.
Thanks.
Use System.Timers.Timer or System.Threading.Timer instead of the Windows.Windows.Forms.Timer
, and inside the Elapced
event handler whenever you call methods or properties on UI controls use control.InvokeRequired
and control.Invoke
.
the problem with the form timer is that it perform the action on UI thread, From msdn:
Windows timer is designed for a single-threaded environment where UI threads are used to perform processing
Edit: Here is example using System.Timers.Timer
:
private System.Timers.Timer _chatTimer = new System.Timers.Timer();
public Form1()
{
InitializeComponents();
_chatTimer.Interval = 1000;//1 seconds
_chatTimer.Elapsed += OnChatTimerElapsed;
_chatTimer.AutoReset = true;
}
private void OnChatTimerElapsed(object sender, System.Timer.ElapsedEventArts e)
{
//code to perform when timer elapsed.
}
Edit2: Another thing to notice that depending on execution time on the elapsed event handler, if the time required to execute the code on it is larger than 1 second then I suggest you to set _chatTimer.AutoReset
to false and only start the timer after the previous elapsed event is finished. for example check this.
精彩评论