I would have a async call to a function as following:
I'll call a method from the main method, this function should be async, how I do this?
A little example:
private static void Main(string[] args)
{
StartDoingNothingAsync();
Console.WriteLine("test");
Console.Read();
}
private static async void StartDoingNothingAsync()
{
for (var i = 0; i < 5000; i++)
{
//do something
}
Console.WriteLine("leaved");
}
I would first the output "test", before "leaved", how can I practice this?
The simplest option would be to introduce a delay into your async method:
private static async void StartDoingNothingAsync()
{
await Task.Delay(1000);
// This will be called on a thread-pool thread
Console.WriteLine("leaved");
}
That won't guarantee that test will be printed before leaved, but it seems very likely. If you actually want a guarantee, you'd have to pass something into StartDoingNothingAsync that you then signal after printing test... but it's not really clear what you're trying to achieve.
Note that async methods should almost never be void - basically that's only available to allow for async event handlers. Make the method return Task instead - that way your calling code can tell when it's completed. (Even if you don't use that fact in this case, it's a good habit to get into.)
Now that we have a bit more information about what you're trying to achieve, I would recommend not making StartDoingNothingAsync an async method - just use a task instead:
private static void Main(string[] args)
{
Task task = Task.Run(DoSomething);
Console.WriteLine("test");
task.Wait();
Console.Read();
}
static void DoSomething()
{
// Code to run on a separate thread
}
You can do it like this
private static void Main(string[] args)
{
StartDoingNothingAsync();
Console.WriteLine("test");
Console.Read();
}
private static async void StartDoingNothingAsync()
{
await Task.Run(async delegate()
{
for (var i = 0; i < 5000; i++)
{
//do something
}
Console.WriteLine("leaved");
});
}
You can use Task for that. In that case you don't need to mark your function as async:
private static void Main(string[] args)
{
new Task(StartDoingNothing).Start();
Console.WriteLine("test");
Console.Read();
}
private static void StartDoingNothing()
{
for (var i = 0; i < 5000; i++)
{
//do something
}
Console.WriteLine("leaved");
}
Related
I have an async method that has a signature like:
public static async void Run(..)
{
//..
var responseMessage = await client.PostAsync(..);
// ..
using (Stream stream = await responseMessage.Content.ReadAsStreamAsync())
//...
Thread.Sleep(5000);
}
I can this method inside of my console app like this:
static async Task Main(string[] args)
{
for(int x = 1; x < 100; x++)
{
Run(...);
}
}
I want to block/sleep inside of my Run method because of rate limiting, how can I do this?
I tried this:
public static async void Run(...)
{
// ...
Thread.Sleep(5000);
}
But this didn't seem to do anything.
Can someone explain why this didn't work and the correct way?
You need to use Task.Delay when using the async pattern:
static async Task Main(string[] args)
{
for(int x = 1; x < 100; x++)
{
await Run(...);
}
}
public static async Task Run(...)
{
// ...
await Task.Delay(5000);
}
NOTE: I've also changed your Run method to be async so that it can be awaited. Also, async void is generally a bad idea and should typically only be done when writing event handlers.
This question already has an answer here:
async Task vs async void
(1 answer)
Closed 3 years ago.
How would I make the main thread wait until DisplayAdd has displayed the output? If I add a Console.Read() at the end, everything works but is there another way to tell the main thread to wait until Calculate() has finished?
namespace TestDelegate
{
public class Add
{
public delegate void SendResult(int i);
public SendResult WhereToSend;
public async void Calculate (int number)
{
Console.WriteLine("Entered");
int result = number + number;
await Task.Delay(4000);
WhereToSend (result);
// Console.Read();
}
}
}
namespace TestStuff
{
class Program
{
static void Main(string[] args)
{
Add obj = new Add();
Console.WriteLine("Started Calculating");
obj.Calculate(10);
obj.WhereToSend = DisplayAdd;
}
static void DisplayAdd(int value)
{
Console.WriteLine(value);
}
}
}
You can define the delegate as Task return type (awaitable type). With this the method will finish before main thread terminates.
namespace TestDelegate
{
public delegate Task SendResult(int i);
public class Add
{
public SendResult WhereToSend;
public async Task Calculate (int number)
{
Console.WriteLine("Entered");
int result = number + number;
await WhereToSend (result);
}
}
}
namespace TestStuff
{
class Program
{
static void Main(string[] args)
{
Add obj = new Add();
obj.WhereToSend = DisplayAdd;
Console.WriteLine("Started Calculating");
obj.Calculate(10).Wait();
}
static async Task DisplayAdd(int value)
{
// Some awaitable operation like below as per your business logic
await Task.Delay(1);
Console.WriteLine(value);
}
}
}
In above program, I've changed the definition of Calculate method to async Task so that it can be marked for Waitable. The async void method are primarily used for UI events hanlder or fire and forget method.
Please check this dotnetfiddle which demonstrates the scenario.
I'm running a C# console application with .NET 4.5.1. When I run the following function the udpClient.ReceiveAsync() call below silently terminates the program with no exception. How do I debug this?
public async void Run()
{
try
{
var armIpAddress = IPAddress.Parse("239.1.11.1");
using (var udpClient = new UdpClient())
{
udpClient.ExclusiveAddressUse = false;
var ipEndPoint = new IPEndPoint(IPAddress.Any, 12020);
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.ExclusiveAddressUse = false;
udpClient.Client.Bind(ipEndPoint);
udpClient.JoinMulticastGroup(armIpAddress);
while (true)
{
var result = await udpClient.ReceiveAsync();
//...
}
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
}
The call to await udpClient.ReceiveAsync() is not terminating the program nor it is silently failing.
Given that this is happening, I assume you have something like this:
public static void Main(string[] args)
{
...
Run();
}
In an async void method, control is returned to the parent as soon as an await call is reached, so the flow of the program would be something like:
public static void Main(string[] args)
{
...
var armIpAddress = IPAddress.Parse("239.1.11.1");
using (var udpClient = new UdpClient())
{
udpClient.ExclusiveAddressUse = false;
.......
while (true)
{
return;
}
}
}
So the program ends due to no further blocking code.
For this to work as you would expect, change the code to this:
public static void Main(string[] args)
{
...
Run().Wait();
}
public async Task Run() { ... }
Not sure about the calling method, but with the given infomation, I would suggest the following article that has best practices around async await by #Stephen Cleary
It says to avoid async void and I am pasting an excerpt here from the article for quick reference
Async void methods can wreak havoc if the caller isn’t expecting them to be async. When the return type is Task, the caller knows it’s
dealing with a future operation; when the return type is void, the
caller might assume the method is complete by the time it returns.
This problem can crop up in many unexpected ways.
Exceptions from an Async Void Method Can’t Be Caught with Catch
Sometimes when I run code made asynchronous using async and await, I find that some parts of the code don't even get executed. For example in the following code, "Sleeping2" is not shown on the console screen:
public static void Sleeping(int millis)
{
System.Console.WriteLine("Sleeping1");
System.Threading.Thread.Sleep(millis);
System.Console.WriteLine("Sleeping2");
}
public static async void SleepingAsync(int millis)
{
await System.Threading.Tasks.Task.Run(() => Sleeping(millis));
}
public static async void DoSleepingMain()
{
System.Console.WriteLine("DoSleepingMain1");
SleepingAsync(12000);
System.Console.WriteLine("DoSleepingMain2");
}
public static void Main(string[] args)
{
DoSleepingMain();
}
Another example is the following in which neither Sleeping1 or Sleeping2 are displayed. I don't understand this because I await the Task in the DoSleepingMain method.
public static void Sleeping(int millis)
{
System.Console.WriteLine("Sleeping1");
System.Threading.Thread.Sleep(millis);
System.Console.WriteLine("Sleeping2");
}
public static async Task SleepingAsync(int millis)
{
System.Threading.Tasks.Task.Run(() => Sleeping(millis)); //warning: call not awaited
}
public static async void DoSleepingMain()
{
System.Console.WriteLine("DoSleepingMain1");
await SleepingAsync(12000);
System.Console.WriteLine("DoSleepingMain2");
}
public static void Main(string[] args)
{
DoSleepingMain();
}
Any explanation (or pointer to explanations) would be appreciated! Thanks
You've just discovered why you should never write async void.
If you write an async void method, you have no way of knowing when the asynchronous part finishes.
This includes Main(); your program is exiting as soon as it hits the first await.
async methods are mostly useless in console programs; if you really want to try them, you'll need to call .Wait() on the Tasks returned to Main().
Why does the delegate need to call the EndInvoke before the method fires? If i need to call the EndInvoke (which blocks the thread) then its not really an asynchronous call is it?
Here is the code im trying to run.
class Program
{
private delegate void GenerateXmlDelegate();
static void Main(string[] args)
{
GenerateXmlDelegate worker = new GenerateXmlDelegate(GenerateMainXml);
IAsyncResult result = worker.BeginInvoke(null, null);
}
private static void GenerateMainXml()
{
Thread.Sleep(10000);
Console.WriteLine("GenerateMainXml Called by delegate");
}
}
The reason you need to call EndInvoke is to avoid memory leaks; .Net will store information about the function's result (or exception) until you call EndInvoke.
You can call EndInvoke in the completion handler that you give to BeginInvoke and retain the asyncronous nature.
EDIT:
For example:
class Program {
private delegate void GenerateXmlDelegate();
static void Main(string[] args) {
GenerateXmlDelegate worker = new GenerateXmlDelegate(GenerateMainXml);
IAsyncResult result = worker.BeginInvoke(delegate {
try {
worker.EndInvoke();
} catch(...) { ... }
}, null);
}
private static void GenerateMainXml() {
Thread.Sleep(10000);
Console.WriteLine("GenerateMainXml Called by delegate");
}
}
If you want to fire an async call and forget about it, you can use the ThreadPool, like this:
ThreadPool.QueueUserWorkItem(delegate { GenerateMainXml(); });
As SLaks said, EndInvoke insures against memory leaks.
BeginInvoke is still asynchronous; consider the following code:
static void Main() {
Func<double> slowCalculator = new Func<double>(PerformSlowCalculation);
IAsyncResult slowCalculation = slowCalculator.BeginInvoke(null, null);
// lots of stuff to do while slowCalculator is doing its thing
Console.WriteLine("Result is {0}", slowCalculator.EndInvoke(slowCalculation));
}
static double PerformSlowCalculation() {
double result;
// lots and lots of code
return result;
}
If this code were written without the BeginInvoke/EndInvoke calls, PerformSlowCalculation would have to finish before Main could do the rest of its "lots of stuff"; this way, the two can be happening at the same time.
Now, in your example using a GenerateXmlDelegate, you still need EndInvoke even though you're not returning anything. The way to do this is:
static void Main(string[] args) {
GenerateXmlDelegate worker = new GenerateXmlDelegate(GenerateMainXml);
IAsyncResult result = worker.BeginInvoke(GenerateXmlComplete, null);
}
private static void GenerateXmlComplete(IAsyncResult result) {
AsyncResult realResult = result as AsyncResult;
GenerateXmlDelegate worker = result.AsyncDelegate as GenerateXmlDelegate;
worker.EndInvoke();
}