I noticed in all Kephas examples that, when invoking async methods, at the end there is a call to PreserveThreadContext(). What does this do?
Some example:
var result = await dataContext.Query<Document>()
.ToListAsync()
.PreserveThreadContext();
I know about ConfigureAwait(false), is this something similar?
In a way, yes, meaning that in a server environment it includes also a call to ConfigureAwait(false). But it also restores the thread bound culture (and UI culture) upon returning from the async call, so that the strings can be localized in a consistent way. This is due to the fact that you may find yourself in another thread upon returning, where the culture is the default one, not the configured one.
Also, you can add your own behaviors for storing/restoring other thread bound information.
Check for this purpose the class https://github.com/kephas-software/kephas/blob/master/src/Kephas.Core/Application/PreserveCultureThreadContextAppLifecycleBehavior.cs, which adds the culture preservation behavior. Typically, you would implement this in an AppLifecycleBehavior, in the BeforeAppInitializeAsync method.
Related
For my application I need to fetch some data asynchronously and do some initialization for each page. Unfortunately, a constructor does not allow me to make asynchronous calls. I followed this article and put all of my code into the OnAppearing method. However, since then I ran into multiple issues since each platform handles the event a little bit differently. For example, I have pages where you can take pictures, on iOS the OnAppearing is called again every time after the camera is closed while Android doesn't. It doesn't seem like a reliable method for my needs, which is also described here:
Calls to the OnDisappearing and OnAppearing overrides cannot be treated as guaranteed indications of page navigation. For example, on iOS, the OnDisappearing override is called on the active page when the application terminates.
I am searching for a method/way where I can perform my own initialization. The constructor would be perfect for that but I cannot perform anything asynchronously in there. Please do not provide me with any work arounds, I am searching for a solution that is the "recommended" way or maybe someone with a lot of experience can tell me what they are doing. (I also don't want to .Wait() or .Result as it will lock my app)
You can use Stephen Cleary's excellent NotifyTaskCompletion class.
You can read more how it works and what to do/don't in these cases in Microsoft's excellent Async Programming : Patterns for Asynchronous MVVM Applications: Data Binding. The highlights of this topics are:
Let’s walk through the core method
NotifyTaskCompletion.WatchTaskAsync. This method takes a task
representing the asynchronous operation, and (asynchronously) waits
for it to complete. Note that the await does not use
ConfigureAwait(false); I want to return to the UI context before
raising the PropertyChanged notifications. This method violates a
common coding guideline here: It has an empty general catch clause. In
this case, though, that’s exactly what I want. I don’t want to
propagate exceptions directly back to the main UI loop; I want to
capture any exceptions and set properties so that the error handling
is done via data binding. When the task completes, the type raises
PropertyChanged notifications for all the appropriate properties.
A sample usage of it:
public class MainViewModel
{
public MainViewModel()
{
UrlByteCount = new NotifyTaskCompletion<int>(
MyStaticService.CountBytesInUrlAsync("http://www.example.com"));
}
public NotifyTaskCompletion<int> UrlByteCount { get; private set; }
}
Here, the demo is about binding the returned asynchronous value to some bindable property, but of course you can you is without any return value (for simple data loading).
This may be too simple to say, but you CAN run asynchronous tasks in the constructor. Just wrap it in an anonymous Task.
public MyConstructor() {
Task.Run(async () => {
<Your code>
}
}
Be careful when doing this though as you can get into resource conflict issues if you accidentally open the page twice.
Another thing I like to do is use an _isInit flag, which indicates a first time use, and then never again.
C++/WinRT's agile_ref supposedly allows usage of non-agile objects in an agile way.
However, I've found that this fails with at least CoreWindow instances.
As a short example:
void Run()
{
auto window{ CoreWindow::GetForCurrentThread() };
window.Activate();
auto agile_wnd{ make_agile(window) };
ThreadPool::RunAsync([=](const auto&) {
auto other_wnd{ agile_wnd.get() };
other_wnd.SetPointerCapture();
});
auto dispatcher{ window.Dispatcher() };
dispatcher.ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
}
Run() is called on the UI thread, then attempts to create an agile reference and then use it to call the CoreWindow from the thread pool. However, this fails with "The application called an interface that was marshaled for a different thread." Since agile_ref uses RoGetAgileReference internally to marshal the object, and the calls to create the reference and then unmarshal it are both succeeding, this appears to me to be CoreWindow simply refusing to be marshaled at all.
Unless, of course, this is working as intended and the RoGetAgileReference call silently fails to marshal the CoreWindow.
So what causes the SetPointerCapture call to fail, even with the agile_ref?
The error is misleading. Most of the Windows.UI classes are actually agile. The challenge is that they perform an explicit thread check to ensure that you are actually calling them from the appropriate UI thread. That's why an agile_ref won't help. The solution is to use the Dispatcher, which gets you on the correct thread. You can then simply call methods on the object directly.
I just converted my Visual Studio 2015 ASP.NET MVC Core project to Visual Studio 2017...and I get the following Informational messages in my Error List
Message IDE1006 Naming rule violation: Missing suffix: 'Async'
This message occurs in my Controllers that focus on the following:
public async Task<IActionResult> Index()
This also applies to Create, Delete, Details and Edit. The messages show as Informational and applies to over 1,000 occurences in my project. It appears that I need to change Index to IndexAsync
ie.
Change from:
public async Task<IActionResult> Index()
public async Task<IActionResult> Create()
public async Task<IActionResult> Delete(int? id)
public async Task<IActionResult> Details(int? id)
Change to:
public async Task<IActionResult> IndexAsync()
public async Task<IActionResult> CreateAsync()
public async Task<IActionResult> DeleteAsync(int? id)
public async Task<IActionResult> DetailsAysnc(int? id)
This appears to be optional at this time as my project will Build and it's not an issue in VS 2015. I don't mind doing the work,I need confirmation that changing this in Visual Studio 2017 ASP.NET Core is the correct approach.
Microsoft is nudging you in the direction of suffixing your your asynchronous methods with the word async. Why? The release notes for Visual Studio 2017 mention this tidbit.
Task-like return types for async methods: This introduces the ability
to return any task-like type from an async method. Previously these
return types were constrained to Task<T> and Task.
Sounds like it's going to become less obvious which methods are asynchronous just from examining their return types. Suffixing them with async may be a good idea. Before VS was making this "suggestion" there was a previous stack overflow question debating the convention. Stephen Toub from Microsoft addressed it, and I quote.
If a public method is Task-returning and is asynchronous in nature (as
opposed to a method that is known to always execute synchronously to
completion but still returns a Task for some reason), it should have
an “Async” suffix. That’s the guideline. The primary goal here with
the naming is to make it very obvious to a consumer of the
functionality that the method being invoked will likely not complete
all of its work synchronously; it of course also helps with the case
where functionality is exposed with both synchronous and asynchronous
methods such that you need a name difference to distinguish them. How
the method achieves its asynchronous implementation is immaterial to
the naming: whether async/await is used to garner the compiler’s help,
or whether types and methods from System.Threading.Tasks are used
directly (e.g. TaskCompletionSource) doesn’t really matter, as that
doesn’t affect the method’s signature as far as a consumer of the
method is concerned.
Of course, there are always exceptions to a guideline. The most
notable one in the case of naming would be cases where an entire
type’s raison d’etre is to provide async-focused functionality, in
which case having Async on every method would be overkill, e.g. the
methods on Task itself that produce other Tasks.
As for void-returning asynchronous methods, it’s not desirable to have
those in public surface area, since the caller has no good way of
knowing when the asynchronous work has completed. If you must expose a
void-returning asynchronous method publicly, though, you likely do
want to have a name that conveys that asynchronous work is being
initiated, and you could use the “Async” suffix here if it made sense.
Given how rare this case should be, I’d argue it’s really a
case-by-case kind of decision.
I hope that helps, Steve
Bottomline, it's informational. But as Microsoft has expanded the return types beyond Task, it it beggining to look more and more like best practice. Use your own judgement.
I noticed that for MVC Controller classes, that in addition to adding Async to the method name, I needed to add [ActionName("MethodName")] as a method attribute where "MethodName" did not have Async at the end. If I didn't add the ActionName attribute, the code would compile, but the URL would not route to the method unless I added Async in the URL as well. I don't want Async in my URLs so I ended up adding ActionName attributes everywhere. It seems like the MVC routing engine should try to find the Async methods, but it doesn't.
How can I pass context from on asynchronous method call to another one - without using method parameters?
I need the feature to enrich log messages with a kind of flow ID so that I can easily trace all log messages of a specific call method flow.
I use Python's async and await keywords (Python 3.5.x).
You should use Context Variables introduced in Python 3.7, and I have a polyfill for Python < 3.7 as aiocontextvars.
Previous answer:
You may want to take a look at tasklocals and aiolocals.
I solved the problem by setting a custom task factory. It turned out that having a context per task (in comparison to a context per async call) was sufficient for me.
I'm working on aiotask-context package. It's a really simple way of passing context between tasks (called with await or yield from). If you don't wan't to use the package you can still use the idea :).
I'm working on how to propagate it for the ensure_future calls too.
import contextvars
c_id = contextvars.ContextVar("context_id", default=None)
def get_context_id():
return c_id.get()
def set_context_id(value):
c_id.set(value)
I struggled a lot for getting this right. If anyone is still searching for the answer then they can refer here. This works with Python3.7 onwards.
Create an instance of contextvars.ContextVar.
Here you can give the context variable name and a default value for that variable, the default value will be used in case the variable is not found in the current context.
Set the value using the setter and you can get the same value using the getter inside same context.
Define ContextVar at the top level once, and not inside closures(i.e. functions or class etc.) as garbage collection for context is not proper.
As per my understanding, unlike functions, event handler receives the event object as parameter.
Is there any other difference between those two words or both are similar?
Can anyone elaborate both the terms?
It really depends on the specific language and API you are using. In C for instance, event-handlers are usually implemented as functions. in C++ they can also be callable objects. Other languages may offer different options.
It may depend on the language. Event handler is a function which often has a special parameter (in most cases) where the parameter is the event object.
So no, there's really no difference between an event handler and a function. You could easily call an event handler just as you would call a function, except you would have to pass some event object to the event handler function, which is not always the case.
Basically you would never call an event handler as you would call a function, you would have something invoke the event when something is triggered, that may be the only difference.
I hope this post is helpful.
Well, event handlers are specific to the framework you use. Java's GUI model is based on even handlers, typically you pass an anonymous inner class that implements the expected interface (like KeyListener) to the addKeyListener (or similar) method.
In C, you typically use function pointers to the same effect. A button struct would hold a function pointer to a callback, and this function could be passed an event struct.
C++ allows you to use the function-pointer idea, or you can define an object that runs some method when you try to 'call' it - some_obj() on a suitably-defined object would call some function of your choice. You could even make it take arguments. Python is like this as well.
If a callback takes a parameter that specifies the event, it's typically called an event handler. But they can be used pretty much interchangeably.