Weird issue with await operator - c#

I had a weird problem today...
My code is running stuck on the await method in c# (no error or sth).
user = await JsonConvert.DeserializeObjectAsync<User>(content);
but when i remove the "await" my code works...
user = JsonConvert.DeserializeObjectAsync<User>(content).Result;
I have the same problem with my HttpClient:
Works
using (HttpResponseMessage response = client.PostAsync(url, posts).Result)
Doesn't work
using (HttpResponseMessage response = await client.PostAsync(url, posts))
the problem wasn't there the day before and if i place my code in another class it works properly
output:
The thread 0xe44 has exited with code 259 (0x103).
The thread 0x81c has exited with code 259 (0x103).
The thread 0x150c has exited with code 259 (0x103).
The thread 0x1660 has exited with code 259 (0x103).
I rebuilded and I have still that problem.
Does someone know the answer?

You are running into a common deadlock issue that I describe on my blog.
To solve it, use await all the way; remove any Task.Wait or Task<T>.Result calls from your code.

Related

Calling URL from Visual Studio on Mac. GetAsync never returns

I have did this several times on Visual Studio C# on Windows.
Now I am using my Mac - creating a Xamarin App in Visual Studio C# and this simple code does not work:
using (HttpClient myClient = new())
{
myClient.DefaultRequestHeaders.Accept.Clear();
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await myClient.GetAsync(url);
string result = await response.Content.ReadAsStringAsync();
return result;
}
The url is: "http://webcode.me".
I tried to create a URI, same issue.
What happens is, that when the code line:
HttpResponseMessage response = await myClient.GetAsync(url);
is called, it never returns. And the app never starts.
Of course, the url I am using is just a test url, but after calling this method, my output window looks like this:
2021-04-16 15:40:07.653142+0200 PHC.iOS[3243:87620] Starting Up
Resolved pending breakpoint at 'Main.cs:35,1' to void PHC.iOS.Application.<GetBridges>d__2.MoveNext () [0x000b2].
Resolved pending breakpoint at 'Communicator.cs:44,1' to void PHC.BridgeCommunication.Communicator.<DoGet>d__4.MoveNext () [0x00189].
2021-04-16 15:40:07.664131+0200 PHC.iOS[3243:87620] Now trying URL: http://webcode.me
Resolved pending breakpoint at 'Communicator.cs:58,1' to void PHC.BridgeCommunication.Communicator.<DoGet>d__4.MoveNext () [0x001b9].
Thread started: #2
2021-04-16 15:40:08.249780+0200 PHC.iOS[3243:87661] SecTaskLoadEntitlements failed error=22 cs_flags=200, pid=3243
2021-04-16 15:40:08.250077+0200 PHC.iOS[3243:87661] SecTaskCopyDebugDescription: PHC.iOS[3243]/0#-1 LF=0
2021-04-16 15:40:08.259552+0200 PHC.iOS[3243:87661] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
Thread started: #3
Thread started: #4
Thread started: <Thread Pool> #5
Thread started: <Thread Pool> #6
And it continues forever with the Thread starting and Thread stopping information.
The "Starting Up" and "Now trying URL: http://webcode.me" are console output from the class calling this function. After writing these things in the console, the method shown above is called.
I can get things to work on my Windows Visual Studio, with no problems at all.
I am NOT Mac-expert, but I am wondering if my Mac is somehow blocking the call. The firewall is turned off.
Can anyone help me a bit?
Okay - first of all. The error had nothing to do with the API-call. The API-call was made async, and the application continued and ran into that error.
I removed the API-call and figured that out.
Then I changed from using HttpClient to use HttpWebRequest and suddenly my requests went through and returned nicely.
I still don't know why my HttpClient did not work at all, but I will close this ticket as I am not in need for answers anymore. Thank you for your comment everyone.

My unit test is always pending

First time attempting to use unit tests. I'm going to go through my steps:
Right clicked solution of my project I want to test in visual studio and clicked 'new project'. Then I selected Test > Test Project.
This gave me another project under my solution with a Test.cs file. I added the following to it:
namespace TestProject1
{
[TestClass]
public class MainTest
{
//Project1.MainWindow mw = new Project1.MainWindow(); //not used in test yet
[TestMethod]
public void MakeDoubleDate_Test()
{
string validMpacString = "1998,265/302010"; //When converted, should be 36060.430902777778
string nonValidString1 = "nope,700/807060";
string nonValidString2 = "thisDoesn't work";
double validDouble = Project1.ConversionsUnit.MakeDoubleDate(validMpacString);
double nonValidDouble1 = Project1.ConversionsUnit.MakeDoubleDate(nonValidString1);
double nonValidDouble2 = Project1.ConversionsUnit.MakeDoubleDate(nonValidString2);
Assert.AreEqual(validDouble, 36060.430902777778);
Assert.AreEqual(nonValidDouble1, DateTime.Now.ToOADate());
Assert.AreEqual(nonValidDouble2, DateTime.Now.ToOADate());
}
}
}
My original project is called Project1. In my test project, I added a reference to Project1.
Now, my test shows up in the test view, but trying to run it it just is stuck on pending forever. I tried another person's project w/ tests and it did the same thing. Not sure what I need to do. Haven't had any luck snooping around google.
Edit: Here's some Debug output when I try running it:
The thread 'ExecutionUtilities.InvokeWithTimeout helper thread 'Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter.AbortTestRun'' (0x4748) has exited with code 0 (0x0).
The thread 'Agent: adapter run thread for test 'MakeDoubleDate_Test' with id '1bc08c40-ee7f-46e5-8689-8237cd3ffe4b'' (0x2820) has exited with code 0 (0x0).
The thread 'Agent: state execution thread for test 'MakeDoubleDate_Test' with id '1bc08c40-ee7f-46e5-8689-8237cd3ffe4b'' (0x1848) has exited with code 0 (0x0).
The thread 'Agent: test queue thread' (0x3ecc) has exited with code 0 (0x0).
W, 18160, 8, 2016/03/29, 12:52:54.995, USERNAME\QTAgent32.exe, AgentObject.AgentStateWaiting: Proceeding to clean up data collectors since connection to controller is lost
The thread 'Agent: heartbeat thread' (0x4560) has exited with code 0 (0x0).
The thread '<No Name>' (0x2284) has exited with code 0 (0x0).
The thread '<No Name>' (0x4484) has exited with code 0 (0x0).
The thread '<No Name>' (0x43f4) has exited with code 0 (0x0).
The thread '<No Name>' (0x3a50) has exited with code 0 (0x0).
The thread '<No Name>' (0x4424) has exited with code 0 (0x0).
Which continues until I exit out of visual studio.
Edit: Saw something about visual studio 2010 having problems w/o service pack 1. Turns out I don't have it. Updating now, hopefully it works.
Updating my visual studio 2010 to service pack 1 solved the issue and my tests run correctly now.
Got the idea to do so from this link: VS2010 Unit test “Pending” and the test cannot be completed

Strange behaviour when using SqlDataReader, StreamWriter and FileStream in MVC application vs Console application

I created a method (OutputFile) that takes in data using a SqlDataReader and then outputs it to a local file using a StreamWriter.
To test that the method output the correct data I created a console application and when the function is called from this it takes roughly 4 minutes which was expected as the stored procedure involved returns a lot of rows (~200,000).
public void OutputFile(string query, string path, params object[] parameters)
{
string connectionString = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
// Open connection
con.Open();
Debug.WriteLine("Starting FileStream");
using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
Debug.WriteLine("Execute Reader");
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
Debug.WriteLine("Writing Files");
while (reader.Read())
{
char[] buffer = new char[4096];
int charsRead = 0;
using (TextReader data = reader.GetTextReader(0))
{
charsRead = data.Read(buffer, 0, buffer.Length);
if (charsRead > 0)
{
writer.WriteLine(buffer, 0, charsRead);
}
}
}
}
}
}
}
}
}
When I moved the method into my ASP.NET MVC application the execution time increased greatly. The first time I ran the application it took 14 minutes to output the file and the second time it took 30 minutes. I have included the output from the debug windows below.
When running the application I made sure to turn check thrown CLR exceptions, but none were thrown.
Thanks in for advance for any help that can explain why this issue is occurring.
Additional notes about the ASP.NET MVC application (the console application did not include these references)
Uses Entity Framework and Unity Framework
Uses Glimpse
Debug output from the file that is produced in 14 minutes
Starting FileStream
Execute Reader
The thread 0x56c has exited with code 259 (0x103).
The thread 0x1194 has exited with code 259 (0x103).
The thread 0x568 has exited with code 0 (0x0).
The thread 0x13f8 has exited with code 259 (0x103).
The thread 0xb6c has exited with code 259 (0x103).
Writing Files
The thread 0xfa8 has exited with code 259 (0x103).
The thread 0x136c has exited with code 259 (0x103).
Debug output from the file that is produced in 30 minutes
Starting FileStream
Execute Reader
The thread 0x1290 has exited with code 259 (0x103).
The thread 0x1030 has exited with code 259 (0x103).
The thread 0x11cc has exited with code 259 (0x103).
The thread 0x1310 has exited with code 259 (0x103).
The thread 0x1d4 has exited with code 259 (0x103).
The thread 0xbb8 has exited with code 259 (0x103).
The thread 0x179c has exited with code 259 (0x103).
The thread 0x1390 has exited with code 259 (0x103).
The thread 0x169c has exited with code 259 (0x103).
The thread 0x16a0 has exited with code 259 (0x103).
The thread 0x1424 has exited with code 259 (0x103).
The thread 0x16e8 has exited with code 259 (0x103).
The thread 0x14f0 has exited with code 259 (0x103).
The thread 0x1458 has exited with code 259 (0x103).
The thread 0x17f8 has exited with code 259 (0x103).
The thread 0x1094 has exited with code 259 (0x103).
The thread 0x1484 has exited with code 259 (0x103).
The thread 0x1540 has exited with code 259 (0x103).
The thread 0x1694 has exited with code 259 (0x103).
The thread 0x17c8 has exited with code 259 (0x103).
The thread 0x1660 has exited with code 259 (0x103).
The thread 0x1764 has exited with code 259 (0x103).
The thread 0x1548 has exited with code 259 (0x103).
The thread 0x172c has exited with code 259 (0x103).
The thread 0x17d8 has exited with code 259 (0x103).
The thread 0x1674 has exited with code 259 (0x103).
The thread 0x1380 has exited with code 259 (0x103).
Writing Files
The thread 0x16a8 has exited with code 259 (0x103).
The thread exit messages are from other threads on the web server, may not necessarily be your request thread (Since webservers are multi-threaded)
Try using a StringBuilder and than writing everything to the file using System.IO.File.WriteAllText instead of using a file stream
If you need to append to an existing file System.IO.File.AppendAllText would work as well
Also, for SQL try using a SqlDataAdapter and copying the entire result into a DataSet and using Table[0] to loop through the data
Hope this explains

My program would close after opening my next form

My second form won't open, willing to give more details if needed
After clicking on the button, it will proceed to the next form but it just closes before it there
private void btnNext_Click(object sender, EventArgs e)
{
frmGame_3_ v = new frmGame_3_();
this.Close();
v.Show();
}
This is what shows when the program closes on me.
The thread 0x21fc has exited with code 259 (0x103). The thread 0x22b8
has exited with code 259 (0x103). 'ICSCulminating.vshost.exe' (CLR
v4.0.30319: ICSCulminating.vshost.exe): Loaded
'C:\Users\Owner\Desktop\ICSCulminating(David)e3\ICSCulminating\bin\Debug\ICSCulminating.exe'.
Symbols loaded. The thread 0x207c has exited with code 259 (0x103).
The thread 0x23c4 has exited with code 259 (0x103). The program
'[7568] ICSCulminating.vshost.exe' has exited with code 0 (0x0).
You can, as suggested by commenter adv12, hide the form instead of closing it. This avoids the problem of the closing of the main form causing your event loop to terminate and the program to exit.
However, it means you are leaving the unused form around, undisposed. IMHO, even if this is not a serious problem per se, it would be better to fix the issue in a cleaner way.
That is, change your program's Main() method so that it uses the parameter-less overload of the Application.Run() method. This removes the dependency on the initial form so that you can close it without the whole program exiting. Then, when you to want to close the program, you can call the Application.ExitThread() method (or Application.Exit() if you prefer).
In your Main() method (found in the Program.cs file of your project), change the last line of the method, which will look something like this:
Application.Run(new Form1());
…to this:
new Form1().Show();
Application.Run();
Note: the name of your main Form subclass may be something other than Form1. Obviously, use whatever class name is in your own code now, if it's not Form1.

When I use threads to print things to the console, why does it produce odd results?

I've been getting into Threads lately while reading the very nice pdf from Rob Miles (here). He had an example on page 160 (2012, C# pdf) but it didn't write to the console just did empty loops.
I wrote a very simple thread producing loop that creates 10 threads that are writing their IDs to the screen on each multiple of 1000. This was nice - it showed me how threads were running together. My Questions begins with why is my output so confused? Often when I run the program below, I get multiple "Thread 3 Finished" lines where I'm pretty certain, I should only have one of each.
I added a "lock" from MSDN to the loop but it still seems to produce odd output (I'll put an example below).
namespace ConsoleApplication1
{
class Program
{
static object sync = new object();
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Thread myThread = new Thread(() => DoThis(i));
myThread.Start();
}
Console.ReadLine();
}
static void DoThis(int s)
{
lock (sync) // a new addition that hasn't helped
{
for (long j = 0; j < 10000; j++)
{
if (j % 1000 == 0) Console.Write(String.Format("{0}.", s));
}
Console.WriteLine("\r\nThread {0} Finished", s);
Debug.Print("\r\nThread {0} Finished", s); //<-- added to debug
}
}
}
}
I thought I was doing okay - I have local variables (my counting loop), I have an int that is passed presumably not by reference and later I tried to lock it while doing it's loop. No joy.What would I need to do to make the output look sensible? I tried Deubg.Print to troubleshoot but it has errors too (below).
Eventually, I want to use threading in a larger application but if I can't get it right here, I'm not sure I want to!
Example Output from the debug.print line at the end: (note the multiples) ...
Thread 1 Done
The thread '<No Name>' (0x15cc) has exited with code 0 (0x0).
Thread 9 Done
The thread '<No Name>' (0x1d0c) has exited with code 0 (0x0).
Thread 6 Done
The thread '<No Name>' (0x2248) has exited with code 0 (0x0).
Thread 10 Done
The thread '<No Name>' (0x22bc) has exited with code 0 (0x0).
Thread 9 Done
The thread '<No Name>' (0x85c) has exited with code 0 (0x0).
Thread 9 Done
The thread '<No Name>' (0x1628) has exited with code 0 (0x0).
Thread 3 Done
The thread '<No Name>' (0x2384) has exited with code 0 (0x0).
Thread 6 Done
Thread 2 Done
Thread 4 Done
The thread '<No Name>' (0x2348) has exited with code 0 (0x0).
The thread '<No Name>' (0x2420) has exited with code 0 (0x0).
The thread '<No Name>' (0x1ea8) has exited with code 0 (0x0).
Let me know if I can offer any more info on what I've tried.
Your problem here is that you are using a "modified closure" on the loop variable.
Although this has been fixed for foreach loops, for loops still have the issue (and always will)
To fix it, change your Main() to this:
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
int copy = i; // Make a copy of i to prevent the "modified closure" problem.
Thread myThread = new Thread(() => DoThis(copy));
myThread.Start();
}
Console.ReadLine();
}
See here for more details:
Access to Modified Closure
Eric Lippert's Article on Closures
Try using Parallel.For instead of starting threads yourself in a loop:
Parallel.For(0, 10, DoThis);
If you needed to pass an extra argument (say w) as part of that, then you can do this:
var w = 4;
Parallel.For(0, 10, i => DoThis(i, w));
The other thing to consider of course is that the Console object is exclusive. If you use it from one thread, any other threads that try to use it will be blocked until it's finished with.
Also your lock (sync) is going to stop any two threads from doing their operation at the same time.
Bear in mind that your threads are not guaranteed to execute in any particular order.

Categories