Does .NET 6's PeriodicTimer capture the current SynchronizationContext by default? - c#

For PeriodicTimer (AsyncTimer at the time), regarding WaitForNextTickAsync, David Fowler mentioned "The execution context isn't captured" (here) via (here). However, given that was not necessarily the final implementation, I reviewed the PeriodicTimer documentation which makes no mention of context capturing.
Based on Stephen Toub's decade old, but still excellent, "The Task-based Asynchronous Pattern," and the following code:
private CancellationTokenSource tokenSource;
private async void start_Click(object sender, EventArgs e)
{
tokenSource = new CancellationTokenSource();
var second = TimeSpan.FromSeconds(1);
using var timer = new PeriodicTimer(second);
try
{
while (await timer.WaitForNextTickAsync(tokenSource.Token).ConfigureAwait(false))
{
if (txtMessages.InvokeRequired)
{
txtMessages.Invoke(() => txtMessages.AppendText("Invoke Required..." + Environment.NewLine));
}
else
{
txtMessages.AppendText("Invoke NOT Required!" + Environment.NewLine);
}
}
} catch (OperationCanceledException)
{
//disregard the cancellation
}
}
private void stop_Click(object sender, EventArgs e)
{
tokenSource.Cancel();
}
If ConfigureAwait is passed true (or removed entirely), my output is as follows:
Invoke NOT Required!
Invoke NOT Required!
Invoke NOT Required!
Invoke NOT Required!
...
However, if ConfigureAwait is passed false, my output is as follows:
Invoke Required...
Invoke Required...
Invoke Required...
Invoke Required...
...
Unless I'm confusing SynchronizationContext with "executing thread," it seems like the current SynchronizationContext IS captured by default. Can anyone (maybe one of the greats) please clarify?

The new (.NET 6) PeriodicTimer component is not like all other Timer components that raise events or execute callbacks. This one resembles more the Task.Delay method. It exposes a single asynchronous method, the method WaitForNextTickAsync. This method is not special in any way. It returns a standard ValueTask<bool>, not some kind of exotic awaitable like the Task.Yield method (YieldAwaitable).
When you await this task, you control the SynchronizationContext-capturing behavior of the await like you do for any other Task or ValueTask: with the ConfigureAwait method. If you know how to use the ConfigureAwait with the Task.Delay, you also know how to use it with the PeriodicTimer.WaitForNextTickAsync. There is absolutely no difference.
If you don't know what the ConfigureAwait does, or you want to refresh your memory, there is a plethora of good articles to read. For the sake of variance I'll suggest this old 5-minute video by Lucian Wischik: Tip 6: Async library methods should consider using Task.ConfigureAwait(false)

Related

When to use asynchronous programming with delegates?

They seem to be doing the same thing, but I don't know when I'm supposed to use tasks and when normal delegates.
Consider the example below:
private async void Button_Click(object sender, RoutedEventArgs e) {
UseDelegates();
// await UseTasks();
}
private void UseDelegates() {
Action action = () => {
Thread.Sleep(TimeSpan.FromSeconds(2));
};
var result = action.BeginInvoke(unusedResult => {
MessageBox.Show("Used delegate.BeginInvoke!");
}, null);
action.EndInvoke(result);
}
private async Task UseTasks() {
await Task.Run(() => {
Thread.Sleep(TimeSpan.FromSeconds(2));
});
MessageBox.Show("Used await with tasks!");
}
There is no truly asynchronous work being done in your example. It seems like the only thing you want to do is to offload some synchronous work to a background thread in order to keep the UI thread responsive during the time it takes for the synchronous method - Thread.Sleep in this case - to complete.
As stated on MSDN; starting with the .NET Framework 4, the Task Parallel Library (TPL) is the preferred way to write multithreaded and parallel code. That's what your UseTasks() method does, i.e. it uses Task.Run to schedule the call to Thread.Sleep on a thread pool thread using the TPL's default task scheduler.
The BeginInvoke/EndInvoke pattern is known as the Asynchronous Programming Model (APM). This pattern is no longer recommended for new development as stated here.
So to answer your questions, you are generally "supposed to use tasks" when offloading work to a background thread in .NET 4+ applications.
In the example you have given. I would use Task every time. The library and syntax has been created with the very aim of getting rid of BeginInvoke and EndInvoke type patterns.
The only time you probably don't want to use Task over an older library is in desktop apps that use BackgroundWorker, which is specifically for running long running background work, that wants to report progress easily to the UI thread. This sort of things isn't as elegant with tasks.

Ignoring the return value from an async Task method

Here's the scenario: In my WPF app I'd like to keep a loop running at all times that does various things. This pattern came to mind:
void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
SomeProcessAsync(); //throw away task
}
async Task SomeProcessAsync()
{
while (true)
{
DoSomething();
await Task.Delay(1000);
}
}
The call triggers a warning since the return value is unused. What is the cleanest way to silence that warning?
#pragma warning disable 4014
AddItemsAsync(); //throw away task
#pragma warning restore 4014
This works but it looks so nasty!
Btw, I also could have used a timer but I liked the simplicity of this loop.
As already mentioned in chris' answer, the right solution here is to turn the event handler into an async void method and then use await, so that exceptions are propagated correctly.
But if you really want to ignore the Task, then you can assign it to a variable:
var ignored = SomeProcessAsync();
Or in C# 7.0, you can use discard:
_ = SomeProcessAsync();
You can make the event handler async:
async void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
await SomeProcessAsync(); //throw away task
}
Normally, async void is bad, but it's necessary when an event handler is async and exceptions should be handled here instead of in whatever calls this. You can (and should) use the normal ConfigureAwait(false) if SomeProcessAsync doesn't need the UI context.
My solution is to silence the compiler warning with a little helper method that is reusable:
static class TaskHelpers
{
/// <summary>Signifies that the argument is intentionally ignored.</summary>
public static void DiscardTask(this Task ignored)
{
}
}
And the call looks like this:
AddItemsAsync().DiscardTask();
That's clean and self-documenting. Still looking for a better name for the helper.
Async-await uses threads from the thread pool. Although the number of threads in the thread pool is fairly large, and possibly adjustable, it is still a limited number of threads.
The threads in the thread pool are optimized for short living tasks. They start and finish fast, the results from these thread can be accessed fairly easily. But these advantages come with a cost. If not, all threads would be threads from the thread pool.
If you want to let your thread do something for a fairly long time, it is best to use a regular System.Threading.Thread, possibly wrapped in a System.ComponentModel.BackgroundWorker.
Better to create a task with your delegate code
Task.Factory.StartNew( () => {} );

DispatcherOperation.Task returning immediately

I have a WPF application where I press a button and the following code executes:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
new Thread(
async () =>
{
Action lambda = async () =>
{
await Task.Delay(5000);
MessageBox.Show("Lambda done");
};
await this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, lambda).Task;
MessageBox.Show("Dispatch done");
}).Start();
}
MSDN documentation of DispatcherOperation.Task says : Gets a Task<TResult> that represents the current operation. (It's not a Task<TResult> tho :/)
So I thought awaiting this would mean that the MessageBox.Show("Dispatch done"); will only be executed after the lambda is finished. However, it is not the case. The MessageBox with "Dispatch done" text is shown as soon as the button is pressed, and the one with "Lambda done" text is shown 5 seconds after, as expected.
Can someone explicate this? I don't understand why it is happening.
This line:
Action lambda = async ...
is creating an async void lambda rather than an async Task lambda. One of the (many) problems with async void is that there is no (easy) way to tell when it completes. For this reason, "avoid async void" is one of the best practices in my MSDN article on the subject.
I haven't tried it, but I suspect that Dispatcher.BeginInvoke can only take Action delegates (and not the more async-friendly Func<Task>), in which case it may be better to use Dispatcher.Invoke and pass a Func<Task>. In my own code, though, I avoid Dispatcher entirely; I find it encourages worse code. Instead of Dispatcher, consider using await and/or Progress<T>.

C#/.NET 4.5 - Why does "await Task.WhenAny" never return when provided with a Task.Delay in a WPF application's UI thread?

Given the following code, why does ask.WhenAny never return when provided with a Task.Delay of 1 second? Technically I'm not sure if it does return after a extended amount of time, but it doesn't after 15 seconds or so after which I manually kill the process. According to the documentation I shouldn't be required to manually start the delayTask, and in fact I receive a exception if I try to do so manually.
The code is being called from the UI thread when a user selects a context menu item in a WPF application, although it works fine if I have the click method specified for the context menu item run this code in a new thread.
public void ContextMenuItem_Click(object sender, RoutedEventArgs e)
{
...
SomeMethod();
...
}
public void SomeMethod()
{
...
SomeOtherMethod();
....
}
public void SomeOtherMethod()
{
...
TcpClient client = Connect().Result;
...
}
//In case you're wondering about the override below, these methods are in
//different classes i've just simplified things here a bit so I'm not posting
//pages worth of code.
public override async Task<TcpClient> Connect()
{
...
Task connectTask = tcpClient.ConnectAsync(URI.Host, URI.Port);
Task delayTask = Task.Delay(1000);
if (await Task.WhenAny(connectTask, delayTask) == connectTask)
{
Console.Write("Connected\n");
...
return tcpClient;
}
Console.Write("Timed out\n");
...
return null;
}
If I change ContextMenuItem_Click to the following it works fine
public void ContextMenuItem_Click(object sender, RoutedEventArgs e)
{
...
new Thread(() => SomeMethod()).Start();
...
}
I predict that further up your call stack, you're calling Task.Wait or Task<T>.Result. This will cause a deadlock that I explain in full on my blog.
In short, what happens is that await will (by default) capture the current "context" and use that to resume its async method. In this example, the "context" is the WPF UI context.
So, when your code does its await on the task returned by WhenAll, it captures the WPF UI context. Later, when that task completes, it will attempt to resume on the UI thread. However, if the UI thread is blocked (i.e., in a call to Wait or Result), then the async method cannot continue running and will never complete the task it returned.
The proper solution is to use await instead of Wait or Result. This means your calling code will need to be async, and it will propagate through your code base. Eventually, you'll need to decide how to make your UI asynchronous, which is an art in itself. At least to start with, you'll need an async void event handler or some kind of an asynchronous MVVM command (I explore async MVVM commands in an MSDN article). From there you'll need to design a proper asynchronous UI; i.e., how your UI looks and what actions it permits when asynchronous operations are in progress.

Visual C# .net 2013 & Threads how-to

I'm normally developping in java but I have now to develop a little wpf application using visual c# 2013 and ... it seems to be more complex than java.
So perhaps I will have lot of questions about it.
For the moment I'm working on threads.
And my first question is : what is the difference between that two ways for creating threads
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void Threads_Button_Click_1(object sender, RoutedEventArgs e)
{
Thread th1 = new Thread(doSomething1);
th1.Start();
Thread th2 = new Thread(new ThreadStart(doSomething2));
th2.Start();
}
private void doSomething1()
{
Console.WriteLine("Starting doSomething1");
Thread.Sleep(3000);
Console.WriteLine("Finishing doSomething1");
}
private void doSomething2()
{
Console.WriteLine("Starting doSomething2");
Thread.Sleep(6000);
Console.WriteLine("Finishing doSomething2");
}
}
They are both the same, what you see there happening is syntax sugar called Delegate Inference.
Delegate inference allows you to make a direct assignment of a method
name to a delegate variable, without wrapping it first with a delegate
object.
In simple words, the compiler sees that the doSomething1 method matches a ThreadStart Delegate so just creates one for you. It knows it should match the ThreadStart because that's in one of the constructor's parameters.
For more possibilities (with lambdas etc...) see this blog.
Storment's answer is correct, but I thought I'd chime in with an alternative way of doing what you are doing that is considered best practice: using Tasks. I am assuming that since you are using VS 2013 that you are targeting .NET 4.5 so you also have the async'/awaitkeywords available to you. With your current little example app, you are going to run into trouble if you try to update your UI fromdoSomething1()ordoSomething2()` because only the UI thread can modify UI controls and those methods are running on different threads.
I'd suggest instead doing something like this:
//notice the async keywords in the method declarations
private async void Threads_Button_Click_1(object sender, RoutedEventArgs e)
{
List<Task> tasks = new List<Task>();
tasks.Add(doSomething1());
tasks.Add(doSomething2());
//this will wait until both doSomething1() and doSomething2() are done in a non-blocking fashion
await Task.WhenAll(tasks);
}
private async Task doSomething1()
{
//you can now update UI controls here
Console.WriteLine("Starting doSomething1");
await Task.Delay(3000);
Console.WriteLine("Finishing doSomething1");
}
private async Task doSomething2()
{
//you can now update UI controls here
Console.WriteLine("Starting doSomething2");
await Task.Delay(6000);
Console.WriteLine("Finishing doSomething2");
}
This is obviously much different than what you have right now, but (other users, please correct me if you have a quibble with this statement), with "modern" .NET, you really shouldn't need to spin up your own threads in a WPF application like this. This again assumes you are targeting .NET 4.5, which, by default, VS 2013 will do (to be more pedantic, it would be 4.5.1 but that is immaterial in this context).
If you are interested in using async/await instead, I'd suggest reading up on it, perhaps by starting with the helpful FAQ on the Parallel Programming blog on MSDN and/or with Stephen Cleary's intro blog post.

Categories

Resources