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
As you know, it it a good idea to call Task.ConfigureAwait(false) when you are waiting on a task in a code that does not need to capture a synchronization context, because it can cause deadlocks otherwise.
Well, how often do you need to capture a synchronization context? I my practice, very rarely. In most situations I am working with "library" code that pretty much forces me to use Task.ConfigureAwait(false) all the time.
So my question is pretty simple: why Task.ConfigureAwait(false) is not the default option for a task? Would not it be much better to force "high-level" code to use Task.ConfigureAwait(true)? Is there a historical reason for it, or am I missing something?
Most code that works with .ConfigureAwait(false) also works, although subobtimal, with .ConfigureAwait(true). Yes, not all code, but still most. The current default lets the highest percentage of code work without tinkering with settings that an average programmer might not understand.
A different default would just lead to thousands of questions about why the code does not work, and worse yet, thousands of answers in the form of "Microsoft sucks, they make you write Control.CheckForIllegalCrossThreadCalls = false; in every program. Why isn't that the default?" rather than actually adding the appropriate .ConfigureAwait(true) calls.
Look at the second example solution from that link:
public async void Button1_Click(...)
{
var json = await GetJsonAsync(...);
textBox1.Text = json;
}
public class MyController : ApiController
{
public async Task<string> Get()
{
var json = await GetJsonAsync(...);
return json.ToString();
}
}
If the default behaviour was ConfigureAwait(false), the textBox1.Text = json; statement would execute on a random thread pool thread instead of the UI thread.
Both snippets look like code someone could reasonably write, and by default one of them has to be broken. Since deadlocks are a lot less dangerous and easier to detect than thread-unsafe accesses, picking ConfigureAwait(true) as the default is the more conservative choice.
Just because your typical use case requires ConfigureAwait(false), it doesn't mean that it is the "correct" or most used option.
One of the things async/await is designed for, is to write responsive GUI programs. In such cases, returning to the UI thread after offloading some work to a Task is critical, since UI updates can only happen from the main thread on most Windows GUI platforms. Async/await helps GUI developers do the right thing.
This is not the only example where the default option makes better sense. I can only speculate, but I would suspect that the decision for the ConfigureAwait default is based on making sure async works with as little friction as possible, for the use cases that Microsoft anticipates it will be used for the most. Not everyone writes frameworks.
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 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 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 7 years ago.
Improve this question
I need to define methods in my core interface that return lists. My project heavily relies on the use of async/await so I need to define my core references/interfaces as asynchronous as possible. I also use EF7 for my data-access layer. I currently use IAsyncEnumerable everywhere.
I am currently deciding whether to keep using IAsyncEnumerable or to revert back to using Task<IEnumerable<T>>. IAsyncEnumerable seems promising at this point. EF7 is using it as well. The trouble is, I don't know and can't figure out how to use it. There is almost nothing on the website that tells anyone how to use Ix.Net. There's a ToAsyncEnumerable extension that I can use on IEnumerable objects but this wouldn't do anything asynchronously (or does it??). Another drawback is that given the below signature:
IAsyncEnumerable GetPersons();
Because this isn't a function that returns Task, I can't use async/await inside the function block.
On the other hand, my gut is telling me that I should stick with using Task<IEnumerable<T>>. This of course has it's problems as well. EF does not have an extension method that returns this type. It has a ToArrayAsync and ToListAsync extension method but this of course requires you to call await inside the method because Task<T> isn't covariant. This potentially is a problem because this creates an extra operation which could be avoided if I simply return the Task object.
My questions is: Should I keep using IAsyncEnumerable (preferred) or should I change everything back to Task<IEnumerable<T>> (not preferred)? I'm open to other suggestions as well.
I would go with IAsyncEnumerable. It allows you to keep your operations both asynchronous and lazy.
Without it you need to return Task<IEnumerble> which means you're loading all the results into memory. This in many cases meaning querying and holding more memory than needed.
The classic case is having a query that the user calls Any on. If it's Task<IEnumerable> it will load all the results into memory first, and if it's IAsyncEnumerable loading one result will be enough.
Also relevant is that with Task<IEnumerable> you need to hold the entire result set in memory at the same time while with IAsyncEnumerable you can "stream" the results a few at a time.
Also, that's the direction the ecosystem is heading. It was added by reactive extension, by a new library suggested by Stephen Toub just this week and will probably be supported in the next version of C# natively.
You should just use Task<IEnumerable<T>> return types. The reason is simply that you don’t want to lazily run a new query against the database for every object you want to read, so just let EF query those at once, and then pass that collection on.
Of course you could make the async list into an async enumerable then, but why bother. Once you have the data in memory, there’s no reason to artificially delay access to it.
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.
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.
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
Which is best?
private long sumVals()
{
return (dbReturn("NUns") / dbReturn("TSpd")) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
or
private long sumVals()
{
long numUnits = dbReturn("NUns");
long targetSpeed = dbReturn("TSpd");
return (numUnits / targetSpeed) * 60;
}
private long dbReturn(string dbField)
{
// ... access db, get value
return retVal;
}
Is it better to try and put it all onto one line, so there is less code overall, or to spread it out like in the second one?
Is one or the other quicker? Is there a benefit, eg, while compiling?
Your case is simple, so the first one is OK. But in general, I would go for the second one.
It is important that you (and others) can read the code, but you don't need to save memory (fewer lines of code as well as fewer variables).
Your code will be easier to understand and debug if you choose to write it the second way. You also don't have to have a lot of comments if your variable names explain the code well enough, which makes your code easier to read in general. (I am not telling you to stop commenting, but to write code which does not need trivial comments!)
See this question for more answers.
My rule of thumb is to include enough content to fully describe what the intent of the code is, and no more. In my opinion, assigning values to variables only to use those variables immediately is actually less readable. It communicates the flow of the program well enough, but doesn't communicate the actual intent.
If you renamed the function from dbReturn to GetDatabaseValue then I don't think I can come up with a more expressive way to write this function than:
return (GetDatabaseValue("NUns") / GetDatabaseValue("TSpd")) * 60);
This communicates the intent perfectly (notwithstanding the fact that I don't know what "NUns" and "TSpd" mean). Fewer symbols means fewer things to understand when reading the code.
Full disclosure: Including extra symbols does improve debuggability. I write this way when I am first building a function so that I can track down where things go wrong. But, when I am satisfied with the implementation, I compress it down as much as possible for my and my co-workers' sanity.
As far as I can tell, there would be no run-time performance gain achieved by either approach. Compilers are awesome - they do this inlining without your knowledge. The only difference is in the code's readability.
To me, longer is always better. Modern compilers will shrink most code to be very fast. However, being able to maintain code through lots of comments and easy-to-read code is hugely important.... especially if you are one of those guys who have to maintain someone else's code!
So, my vote is the longer version (with a comment explaining what you are doing too!)