All Questions
2,508
questions
722
votes
6
answers
587k
views
async/await - when to return a Task vs void?
Under what scenarios would one want to use
public async Task AsyncMethod(int num)
instead of
public async void AsyncMethod(int num)
The only scenario that I can think of is if you need the task ...
455
votes
18
answers
1.6m
views
How do I make calls to a REST API using C#?
This is the code I have so far:
public class Class1
{
private const string URL = "https://sub.domain.com/objects.json?api_key=123";
private const string DATA = @"...
421
votes
12
answers
232k
views
Do HttpClient and HttpClientHandler have to be disposed between requests?
System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker).
The using statement documentation says:
As a ...
377
votes
3
answers
443k
views
Do you have to put Task.Run in a method to make it async?
I'm trying to understand async await in the simplest form. I want to create a very simple method that adds two numbers for the sake of this example, granted, it's no processing time at all, it's just ...
221
votes
6
answers
98k
views
What's the difference between Task.Start/Wait and Async/Await?
I may be missing something but what is the difference between doing:
public void MyMethod()
{
Task t = Task.Factory.StartNew(DoSomethingThatTakesTime);
t.Wait();
UpdateLabelToSayItsComplete();
}...
212
votes
4
answers
163k
views
Using 'async' in a console application in C# [duplicate]
I have this simple code:
public static async Task<int> SumTwoOperationsAsync()
{
var firstTask = GetOperationOneAsync();
var secondTask = GetOperationTwoAsync();
return await ...
209
votes
11
answers
111k
views
Is it possible to await an event instead of another async method?
In my C#/XAML metro app, there's a button which kicks off a long-running process. So, as recommended, I'm using async/await to make sure the UI thread doesn't get blocked:
private async void ...
200
votes
10
answers
337k
views
C# HttpClient 4.5 multipart/form-data upload
Does anyone know how to use the HttpClient in .Net 4.5 with multipart/form-data upload?
I couldn't find any examples on the internet.
190
votes
5
answers
119k
views
Async/await vs BackgroundWorker
In the past few days I have tested the new features of .net 4.5 and c# 5.
I like its new async/await features. Earlier I had used BackgroundWorker to handle longer processes in the background with ...
190
votes
4
answers
225k
views
How to cancel a Task in await?
I'm playing with these Windows 8 WinRT tasks, and I'm trying to cancel a task using the method below, and it works to some point. The CancelNotification method DOES get called, which makes you think ...
184
votes
19
answers
92k
views
Cleaner way to do a null check in C#? [duplicate]
Suppose, I have this interface,
interface IContact
{
IAddress address { get; set; }
}
interface IAddress
{
string city { get; set; }
}
class Person : IPerson
{
public IContact contact { ...
184
votes
1
answer
6k
views
Catch-22 prevents streamed TCP WCF service securable by WIF; ruining my Christmas, mental health
I have a requirement to secure a streamed WCF net.tcp service endpoint using WIF. It should authenticate incoming calls against our token server. The service is streamed because it is designed to ...
155
votes
2
answers
168k
views
How does Task<int> become an int?
We have this method:
async Task<int> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
...
149
votes
6
answers
199k
views
Run two async tasks in parallel and collect results in .NET 4.5
I've been trying for a while to get something I thought would be simple working with .NET 4.5
I want to fire off two long running tasks at same time and collect the
results in in the best C# 4.5 (...
132
votes
3
answers
48k
views
Is async HttpClient from .Net 4.5 a bad choice for intensive load applications?
I recently created a simple application for testing the HTTP call throughput that can be generated in an asynchronous manner vs a classical multithreaded approach.
The application is a able to ...
115
votes
29
answers
263k
views
The type or namespace name 'System' could not be found
I have the following errors (and more) in all my views (*.cshtml) when opening my project in Visual Studio 2015 Professional.
Error CS0246 The type or namespace name 'System' could not be found (...
112
votes
2
answers
113k
views
HttpClient.GetAsync with network credentials
I'm currently using HttpWebRequest to get a website. I'd like to use the await pattern, which is not given for HttpWebRequests. I found the class HttpClient, which seems to be the new Http worker ...
103
votes
3
answers
83k
views
Proper way to implement a never ending task. (Timers vs Task)
So, my app needs to perform an action almost continuously (with a pause of 10 seconds or so between each run) for as long as the app is running or a cancellation is requested. The work it needs to do ...
100
votes
1
answer
90k
views
Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type
I am working with .NET4.5 and VS2013, I have this query that gets dynamic result from db.
dynamic topAgents = this._dataContext.Sql(
"select t.create_user_id as \"User\", sum(t.netamount) as \"...
88
votes
6
answers
138k
views
Is it possible to run a .NET 4.5 app on XP?
First, I have read the following:
Connect case
VS case
and especially this channel9 post
So, from the last bullet, I really think there is no way around this, but I had to see if I could get a ...
87
votes
13
answers
137k
views
How to 'await' raising an EventHandler event
Sometimes the event pattern is used to raise events in MVVM applications by or a child viewmodel to send a message to its parent viewmodel in a loosely coupled way like this.
Parent ViewModel
...
86
votes
9
answers
39k
views
How can I create a new instance of ImmutableDictionary?
I would like to write something like this:
var d = new ImmutableDictionary<string, int> { { "a", 1 }, { "b", 2 } };
(using ImmutableDictionary from System.Collections.Immutable). It seems like ...
85
votes
4
answers
39k
views
What's the difference between InvokeAsync and BeginInvoke for WPF Dispatcher
I noticed in .NET 4.5 that the WPF Dispatcher had gotten a new set of methods to execute stuff on the Dispatcher's thread called InvokeAsync. Before, .NET 4.5 we had Invoke and BeginInvoke which ...
82
votes
3
answers
142k
views
Which versions of SSL/TLS does System.Net.WebRequest support?
Now that SSL 3 has been found to be vulnerable to the POODLE attack:
Which versions of SSL/TLS does System.Net.WebRequest use when connecting to any https Uri?
I use WebRequest to connect to ...
79
votes
1
answer
148k
views
Await operator can only be used within an Async method [duplicate]
I'm trying to make a simple program to test the new .NET async functionality within Visual Studio 2012. I generally use BackgroundWorkers to run time-consuming code asynchronously, but sometimes it ...
75
votes
4
answers
41k
views
HTTP HEAD request with HttpClient in .NET 4.5 and C#
Is it possible to create a HTTP HEAD request with the new HttpClient in .NET 4.5? The only methods I can find are GetAsync, DeleteAsync, PutAsync and PostAsync. I know that the HttpWebRequest-class is ...
72
votes
4
answers
34k
views
OWIN HttpListener not located
When I try to start :
WebApp.Start<SrvcHst>(new StartOptions { Port = 9956,
ServerFactory = "Microsoft.Owin.Host.HttpListener" });
I get the following exception. What could be the root ...
72
votes
3
answers
73k
views
Create zip file from byte[]
I am trying to create a Zip file in .NET 4.5 (System.IO.Compression) from a series of byte arrays. As an example, from an API I am using I end up with a List<Attachment> and each Attachment has ...
69
votes
2
answers
45k
views
Does C# 7.0 work for .NET 4.5?
I created a project in Visual Studio 2017 RC to check whether I can use new C# 7.0 language features in a .NET Framework 4.5 project. It seems to me that after referencing System.ValueTuple NuGet, new ...
69
votes
6
answers
11k
views
Why doesn't generic ICollection implement IReadOnlyCollection in .NET 4.5?
In .NET 4.5 / C# 5, IReadOnlyCollection<T> is declared with a Count property:
public interface IReadOnlyCollection<out T> : IEnumerable<T>, IEnumerable
{
int Count { get; }
}
I ...
66
votes
10
answers
120k
views
Is that possible to send HttpWebRequest using TLS1.2 on .NET 4.0 framework
My application connects to Experian server and Experian will soon stop supporting TLS 1.0 and TLS 1.1. All connectivity using HTTPS must use TLS Version 1.2.
I want to do some research on that issue ...
63
votes
1
answer
26k
views
What can I do in C# 5 with .Net 4.5 that I couldn't do in C# 4 with .Net 4? [closed]
I have Visual Studio 2012 RC installed on Windows 8 Release Preview and my question is are there any useful new features not related to Metro, or is Metro what seperates .Net 4 and .Net 4.5?
61
votes
4
answers
34k
views
What are the differences between using ConfigureAwait(false) and Task.Run?
I understand that it's recommended to use ConfigureAwait(false) for awaits in library code so that subsequent code does not run in the caller's execution context, which could be a UI thread. I also ...
57
votes
10
answers
56k
views
awaitable Task based queue
I'm wondering if there exists an implementation/wrapper for ConcurrentQueue, similar to BlockingCollection where taking from the collection does not block, but is instead asynchronous and will cause ...
53
votes
4
answers
66k
views
IList<T> and IReadOnlyList<T>
If I have a method that requires a parameter that,
Has a Count property
Has an integer indexer (get-only)
What should the type of this parameter be? I would choose IList<T> before .NET 4.5 ...
51
votes
7
answers
18k
views
Awaiting Asynchronous function inside FormClosing Event
I'm having a problem where I cannot await an asynchronous function inside of the FormClosing event which will determine whether the form close should continue. I have created a simple example that ...
50
votes
6
answers
32k
views
Task.Yield - real usages?
I've been reading about Task.Yield , And as a Javascript developer I can tell that's it's job is exactly the same as setTimeout(function (){...},0); in terms of letting the main single thread deal ...
46
votes
1
answer
4k
views
Why doesn't `IList<T>` inherit from `IReadOnlyList<T>`?
When IReadOnlyList<T> was introduced in .NET 4.5, for a moment I thought the missing part of the puzzle was finally inserted in place: a way to pass a true readonly indexable interface where ...
45
votes
3
answers
28k
views
Brief explanation of Async/Await in .Net 4.5
How does Asynchronous tasks (Async/Await) work in .Net 4.5?
Some sample code:
private async Task<bool> TestFunction()
{
var x = await DoesSomethingExists();
var y = await ...
45
votes
9
answers
18k
views
Visual Studio keeps overwriting NewtonSoft.Json.DLL with an older version
Visual Studio is overwriting the correct version of NewtonSoft.Json.DLL that I have configured in both my project references and the NuGet package file with an older version when I build any other ...
45
votes
4
answers
32k
views
Entity Framework - Migrations - Code First - Seeding per Migration
I am looking into Migrations in an effort to clean up our deployment processes. The less manual intervention required when pushing a change to production the better.
I have run into 3 major snags ...
44
votes
11
answers
61k
views
Creating Directories in a ZipArchive C# .Net 4.5
A ZipArchive is a collection of ZipArchiveEntries, and adding/removing "Entries" works nicely.
But it appears there is no notion of directories / nested "Archives". In theory, the class is decoupled ...
44
votes
4
answers
37k
views
EF5 Starting a Project:Error Running transformation: Please overwrite the replacement token '$edmxInputFile$'
I'm creating a Console Project in VS2012 with .Net4.5.
After it I "Add", "New Item" to the project, and choose "EF 5.x DbContext Generator".
Then, after a couple of seconds the following error message ...
43
votes
2
answers
48k
views
Using .Net 4.5 Async Feature for Socket Programming
I've previously used BeginAccept() and BeginRead(), but with Visual Studio 2012 I want to make use of the new asynchronous (async, await) features in my socket server program.
How can I complete the ...
43
votes
6
answers
15k
views
Writing to ZipArchive using the HttpContext OutputStream
I've been trying to get the "new" ZipArchive included in .NET 4.5 (System.IO.Compression.ZipArchive) to work in a ASP.NET site. But it seems like it doesn't like writing to the stream of HttpContext....
42
votes
3
answers
2k
views
Changed behavior of string.Empty (or System.String::Empty) in .NET 4.5
Short version:
The C# code
typeof(string).GetField("Empty").SetValue(null, "Hello world!");
Console.WriteLine(string.Empty);
when compiled and run, gives output "Hello world!" under .NET version 4....
42
votes
1
answer
2k
views
SqlDependency Losing Subscription Over Time
I've been using SqlDependency in a .NET 3.5 application for over 3 years without any problems. The scenario is as follows:
Central windows service with a SqlDependency watching a table (let's call ...
41
votes
3
answers
183k
views
What is the correct way to read a serial port using .NET framework?
I've read a lot of questions here about how to read data from serial ports using the .NET SerialPort class but none of the recommended approaches have proven completely efficient for me.
Here is the ...
41
votes
3
answers
30k
views
Creating an async method in .NET 4.0 that can be used with "await" in .NET 4.5
I have a .NET project that uses C# in .NET 4.0 and VS2010.
What I would like to do is add some async overloads to my library to make doing async programming easier for users in .NET 4.5 with the ...
40
votes
1
answer
9k
views
Is performance hit by using Caller Information attributes?
I am trying to find ways to log method name in an efficient manner w.r.t. speed and maintainability. I guess, In .NET 4.5 Caller Information attributes are exposed just for this purpose except the ...