Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
my app using sql server is located on a server . my problem is a when using this app ، freeze app when get data from server !
What is your proposed solution?
It sounds like you're executing your database query from the UI thread. Perhaps, the query is being executed in a button "click" action handler?
The UI thread is a thread where UI message loop is running and processing UI events (things like button clicks, window resize etc.). If you perform a long running task in the UI thread it will prevent all other UI messages being processed until the task is finished. As a result the UI will look frozen.
Database calls are fairly slow and it's a good idea to execute them outside of the UI thread. One solution is to spin a new thread, providing a callback method to be called once the query execution was completted.
A better approach is to use async/await. You'll have to define an async method that performs a DB call. And then await for that method in your UI thread.
Please show us how you fetch the data from a database and we'll give you more details on how to implement it without blocking the UI.
Without more info here's general advice:
Execute your query on a thread (use a Task if modern), then when thread gets it's data back invoke back on main/UI thread. This will prevent your UI from locking up while querying for data.
You might also want to start a 'spinner' or a 'loading' indicator of some sort on the UI thread so the user knows to wait and doesn't go click-crazy trying to load the data again and again...
Also be sure to include some error handling in your query thread so if things go bad you can recover and alert (messagebox, write to log, whatever you need to do).
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am encountering following issue in my .Net application:
It is a game server so there are around 150 threads to process all time-related logic, and some of them are Threading.Timer instances. The server was running fine at the beginning and to some point all timers stops working. I tried to start new timers via script executor. The new timers could be started but they are not firing events neither.
Anyone has idea about what could cause all the timers stop working in the process? I am not aware how could this happen theoretically.
System.Threading.Timer "executes a single callback method on a thread pool thread at regular intervals". Considering you are using 150 threads, its possible you are exhausing the thread pool.
Additionally, if you handler takes too long to process an event, Timer might fall behind and queue updates.
Re-think your design
Unless its a major component like scene loading; or audio playback; game makers generally avoid threading in games for reasons of reliability and simplicity.
Instead you may want to consider using:
deferred processing - delay processing until some time later
batch processing - rather than processing 10,000 items, process a batch of 100 items every 10ms
Gregory, J, "Game Engine Architecture"
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to read sms from my GSM modem.
I wrote C# code.
This code run when I click start button.
I want to my program read sms when received, not click button.
thanks.
Your program is keyed to activate when you press a button, some method is called. You need to call this method when SMS data is received instead. This could be done using threads (SMS thread and main thread showing data) although it could just as easily be done using a cycle. In pseudo code:
while (don't quit) {
display page;
check for sms data;
sleep for small time to allow other OS programs to run also;
}
This is a "tight loop" and can use excessive amounts of CPU time depending on the code of the actual steps. For a tight program loop one simple method is to apply some sort of sleep method.
There are other ways to do the same thing, visitor pattern could probably be used, threads, etc...
It seems that you are only lacking the cycle. Your programs is probably more like:
while (don't quit) {
display page.
wait for button press.
}
although that flow wouldn't be obviously apparent at first glance without studying your program flow.
If you are using triggers (the button press is probably a trigger) you can trigger on a timer that fires as often as you want (100ms, 1 second, whatever) that checks for SMS data when fired, if there is SMS data it updates the form.
Many, many ways to do this. A quick Google for "program flow" doesn't find any useful links at first glance that would explain the many ways you could do this. Perhaps looking at other's code would help. I've often searched open source repositories for code I could look at to see how someone else did something.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am building an MVC app and in this appllication there are actions that implies some things. So we wish to warn our customers / users using mailing system. I'm building both a local application and a web store, so I'll need to send a lot of mails sometimes.
I am currently using MvcMailer why does nicely its job, but my main concern is that since it occurs during a normal method call (ex: result of an operation, then:
MvcMailMessage msg = mailer.NewOrder(emailTo);
msg.Send();
And the message goes, it takes a while. And since this kind of operation might be called quite a few times, it will overall slow down the whole process, which I do not wish.
So my question is: how should I handle mail processing? Is there an asynchroneous thing I may use that will do the job? Do I store them in a database table and send them sometimes? I've heard about Task in windows .Net, but I've never used any, is that an option?
I'm looking for suggestions, so feel free to share your opinion! Thank you!
You can use SmtpClient.SendMailAsync using the async-await keywords
public async Task SendSmtpMailAsync()
{
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMessage = new MailMessage("FromAddress", "ToAddress", "Subject", "Body");
await smtpClient.SendMailAsync(mailMessage);
// Possibly do more stuff here.
}
When you await on an asynchronous method, control yields back to the caller. What that means is that the ASP.NET can process messages in the meantime using the thread that returned to the ASP
NET ThreadPool from that same method. When the method finishes, it will return back to the awaited line and continue execution.
Note that using this async alone wont return the request to the caller, it will simply let you process more requests in the meanwhile. What you can do is use this method in correlation with a producer-consumer style collection, like BlockingCollection<T>, add your messages to it and return the response to you caller. In the background, use SendMailAsync to execute these requests.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need to generate a GUI for a WinForm in Thread1 using the result of Thread2.
However, Thread1 should start from Thread2.
If the result of Thread2 is equal to 1, I need to show a grid on my WinForm. If not, I need to show a tab control on my WinForm.
The UI thread must build it or atleast add it to the form.
But in Thread 2 you can collect all required information or maybe controls and pass them by invoke or as BackgroundWorker result to the UI thread.
You should only keep a single UI thread, and never create any UI elements in another thread.
Microsoft has many articles on this topic and demonstrates the correct way to handle async operations, such as
http://msdn.microsoft.com/en-us/library/ms951089.aspx
If I understood you correctly there is a need of creating GUI elements in one thread for later using them in GUI thread.
And as far as I remember it is not possible because control remembers the thread it was created on and later checks whether calls are made within that thread.
I'd recommend you to generate data only in background thread and pass it to gui thread where you can bind this data or generate ui elements to represent it. Moreover it conforms to the best practice of separation of concerns.
Lex Li has posted the link in comments to the question devoted to passing data to GUI thread.
I am not sure, I can understand your problem correctly but here is the code to create UI controls in a different thread.
var th = new Thread(() =>
{
//A sample form with a RichTextBox control.
var f = new Form();
f.Controls.Add(new RichTextBox() { Dock = DockStyle.Fill });
Application.Run(f);
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
just a simple question on data updating.
Suppose I have a TextBox called txtBox1 and I want to update the value of a string variable called foo.
Which gives the best performance and best to do?
// The lengthier code but will check if the value is the same before updating.
if (foo != txtBox1.Text)
foo = txtBox1.Text;
or
// The shorter code but will update it regardless if it's the same value
foo = txtBox1.Text;
It really depends on what you do with foo variable.
If updating foo involves updating other parts of your application (via data binding for example) then yes, you should only update it when necessary.
Original Answer
Warning: I messed up... this answer applies for the opposite case, that is:
txtBox1.Text = foo
It may depend on what TextBox you are using...
I haven't reviewed all the clases with that name in the .NET framework from Microsoft. But I can tell for System.Windows.Forms.TextBox that the check is done internally, so doing it yourself is a waste. This is probably the case for the others.
New Answer
Note: This is an edit based on the comments. It it taken from granted that the objective is keep track of the modifications of the texbox and that we are working in windows forms or similar dektop forms solution (that may be WinForms, WPF, GTK#, etc..).
IF you need every value...
TextChanged is the way to go if you want a a log or undo feature where you want to offer each value the textbox was in.
Although take note that the event runs in the same thread as that the text was assigned, and that thread ought to be the thread that created the textbox. Meaning that if you cause any kind of lock or do an expensive operation, it will heavily^1 impact the performance of the form, causing it to react slowly because the thread that must update the form is busy in the TextChanged handler.
^1: heavily compared to the alternative presented below.
If you need to do an expensive operation, what you should do is add the values to a ConcurrentQueue<T> (or similar). And then you can have an async^2 operation run in the background that takes the values from it and process them. Make sure to add to the queue the necessary parameters^3, that way the expensive operation can happen in the background.
^2: It doesn't need to be using the async keyword, it can be a ThreadPool, a Timer, a dedicated Thread or something like that.
^3: for example the text, and the time in the case of a log. If have to monitor multiple controls you could also consider using a POCO (Plain Old CLR Object) class or struct to store all the status that need to be kept.
IF you can miss some values...
Using the event
Use the event to update a version number instead of reading the value.
That is, you are going to keep two integer variables:
The current version number that you will increment when there were a change. Use Thead.VolatireWrite for this (there is no need for Interlocked)
The last checked version number that you will update when you read the values from the form (this done from an async operation), and that you will use to verify if there has been any updates recently. Use Interlocked.Exchange to update the value and proceed if the old value is different from the readed one.
Note: Test the case of aritmetic overflow and make sure it wraps MaxValue to MinValue. No, it will not happen often, but that's no excuse.
Again, under the idea that it is ok to miss some values... If you are using a dedicated Thread for this, you may want to use a WaitHandle (ManualResetEvent or AutoResetEvent [and preferably it's slim counterparts]) to have the thread sleep when there hasn't been modifications instead of having it nopping (spin waiting). You will then set the WaitHandle in the event.