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.
Related
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 2 years ago.
Improve this question
I'm working with Anonymous Pipes to be able to communicate between 2 applications. I have 3 classes. A base class Node which holds the incoming and outgoing streams and methods like Read and Write. Deriving from this class are Client and Server. They each initialize respectively their AnonymousPipeClientStream and AnonymousPipeServerStream and have a method to sync with each other.
Having above code allows me to communicate between the 2 applications. I start the "server" application. This application starts the "client".
When both applications are started I need to send some arguments from the server to the client. The client is basically waiting for messages from the server. On the server I need to start the reading of the arguments on the client, then send the arguments and end the reading on the client so it's free to start another task. To do this I simply need to
write the start command,
write the arguments,
write the end command and
wait for the client to confirm the task is finished.
public void ServerStartClientTask()
{
Write(ReadInputs); // (1)
Write(Arg1); // (2)
Write(Arg2); // (2)
Write(ReadInputs); // (3)
while (WaitFor(ReadInputs)); // (4)
}
This is "straightforward" when you're the writer of the code (in my opinion) and is the convention how communication with the client has to happen. I wanted to make it more clear for myself and my colleagues so I came up with the following:
public void StartClientTask(Flag flag)
{
Write(flag);
}
public void EndClientTask(Flag flag)
{
Write(flag);
while (WaitFor(flag)) { }
}
public void ServerStartClientTask()
{
StartClientTask(ReadInputs); // (1)
Write(Arg1); // (2)
Write(Arg2); // (2)
EndClientTask(ReadInputs); // (3) and (4)
}
This code merely wraps code into another method to make it more readable how the communication is dome with the client.
Now for the question.
This example is not limiting to my question but just the use case I have now and to introduce my question. Is doing this wrapping of code with just other names a good or bad practice? Both examples work perfectly fine, they're just written differently. Is there a benefit to doing the 2nd approuch or would you rather just write a comment at (1), (3) and (4) in the 1st example?
In my opinion this is a very good practice and I use it all the time.
Makes the code very readable for other developers.
this way I rarely have to use comments inside my methods because the names of the methods explain what is happening.
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 4 years ago.
Improve this question
This question is related to entire "async-await" implementation.
I will keep it simple.
Example:
HttpClient client = new HttpClient();
string urlContents = await client.GetStringAsync("http://msdn.microsoft.com");
Is there any reason to use client.GetString()?
Why not just name GetStringAsync as GetString, and get rid of non-async GetString? And get rid of async-await keywords at all?
I read many posts, but didn't find a clear simple explanation.
Why create so many duplicate methods, what's the point? It just doesnt feel right. Give me a reason why use non-async method? Don't you want long running methods to use available threads and CPU cores to run things in parallel?
(obviously it has nothing to do with the web-based ajax async operations)
Why not just name GetStringAsync as GetString, and get rid of non-async GetString?
There are two reasons for this:
Doing so would break backward compatibility - programs that rely on GetString returning a string rather than a Task<string> would stop compiling, and
Requiring await would make it hard to use the API from non-async methods - programmers would need to write additional code to wait for the task to complete.
Each of these considerations is disqualifying by itself.
Note that once your API is in use, you must be extremely cautious about "breaking changes", i.e. changes that break code relying on your API. Changing method's return type, along with a fundamental part of its functionality (synchronous vs. asynchronous) is definitely a breaking change.
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 5 years ago.
Improve this question
So far I have only written single core programs. Now I want to improve my performance and trying to find out, how to pull and push data parallelized. But I even don't know whether I have the right idea about MultiThreading.
Actually it is a pretty simple case. I pull data from an external interface, rework them so that they are in the right order and push them into an OpenGL Pipeline in order to draw them.
I use a WPF-application as GUI and render my data with SharpGL(OpenGL wrapped). the program runs on a dual-core processor.
Here is a sketch of my vision.
So my idea is to use a bufferArray. Now the clue: How could I write and read in the same array from different thrads?
I was recommended to inform about OpenMP. But as it turned out it is not a good idea for .Net and C#.
Thus could you recommend some fitting papers? Maybe an explanation how to use Task Parallel Library (TPL) for this case.
The correct description for this is the producer consumer pattern. In .Net you can do this using TPL Dataflow
Another implementation can be build using a BlockingCollection. A basic version:
BlockingCollection<int> bc = new BlockingCollection<int>();
async Task Main()
{
// Fire up two readers
Task.Run(() => ReadCollection1());
Task.Run(() => ReadCollection2());
// Add items to process.
bc.Add(5);
bc.Add(6);
bc.Add(7);
bc.Add(8);
bc.Add(9);
bc.CompleteAdding(); // Signal we are finished adding items (on close of application for example)
}
void ReadCollection1()
{
foreach (var item in bc.GetConsumingEnumerable())
{
$"1 processed {item}".Dump();
}
}
void ReadCollection2()
{
foreach (var item in bc.GetConsumingEnumerable())
{
$"2 processed {item}".Dump();
}
}
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).
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 a ASP.NET webapplication in which I use several classes containing static functions for retreiving database values and such (based on session of user so their results are session specific, not application wide).
These functions can also be called from markup, which makes developing my GUI fast and easy.
Now I am wondering: is this the right way of doing things, or is it better to create a class, containing these functions and create an instance of the class when needed?
What will happen when there are a lot of visitors to this website? Will a visitor have to wait until the function is 'ready' if it's also called by another session? Or will IIS spread the workload over multiple threads?
Or is this just up to personal preferences and one should test what works best?
EDIT AND ADDITIONAL QUESTION:
I'm using code like this:
public class HandyAdminStuff
{
public static string GetClientName(Guid clientId)
{
Client client = new ClientController().GetClientById(clientId);
return client.Name;
}
}
Will the Client and ClientController classes be disposed of after completion of this function? Will the GarbageCollector dispose of them? Or will they continue to 'live' and bulk up memory everytime the function is called?
** Please, I don't need answers like: 'measure instead of asking', I know that. I'd like to get feedback from people who can give a good answer an maybe some pro's or cons, based on their experience. Thank you.
"Will a visitor have to wait until the function is 'ready' if it's also called by another session?"
Yes. It may happen if you have thread safe function body, or you perform some DB operations within transaction that locks DB.
Take a look at these threads:
http://forums.asp.net/t/1933971.aspx?THEORY%20High%20load%20on%20static%20methods%20How%20does%20net%20handle%20this%20situation%20
Does IIS give each connected user a thread?
It would be better to have instance based objects because they can also be easily disposed (connections possibly?) and you wouldn't have to worry about multithreading issues, additional to all the problems "peek" mentioned.
For example, each and every function of your static DAL layer should be atomic. That is, no variables should be shared between calls inside the dal. It is a common mistake in asp.net to think that [TreadStatic] data is safe to be used inside static functions. The only safe pool for storing per request data is the Context.Items pool, everything else is unsafe.
Edit:
I forgot to answer you question regarding IIS threads. Each and every request from your customers will be handled by a different thread. As long as you are not using Session State, concurrent requests from the same user will be also handled concurrently by different threads.
I would not recommend to use static function for retrieving data. This because these static functions will make your code harder to test, harder to maintain, and can't take advantage of any oo principals for design. You will end up with more duplicate code, etc.