Differences between Async CTP and Bcl.Async when calling async methods as sync - task-parallel-library

I'm currently trying to make a piece of code written in VS 2012, using Microsoft.Bcl.Async and .NET 4.0, work in VS 2010. For VS 2010 I've installed the Async CTP (ver. 3), such that I am able to compile my project written in V S2012.
After quite a lot of trouble getting the Async CTP pack to work, I am now able to compile my project under both VS 2012 as well as VS 2010.
However, I'm seeing some differences in how the code works in run-time. The code I am exercising is shown below:
public class Fetcher
{
public string RunTask()
{
Task<string> task = TaskEx.Run(() => RunTaskAsync());
return task.Result;
}
public async Task<string> RunTaskAsync()
{
await TaskEx.Delay(1);
return "Hello";
}
}
Basically, what I have is an async method, for which I need to have a sync wrapper around, such that clients can call either the async or sync version of the method.
The problem: When running the code from VS 2012 both method will return the result "Hello", and more importantly, both methods will exit properly. Running the code from VS 2010, however, is a far different story. The async method works as intended, but the sync wrapper method simply hangs, and the result is never produced.
Since I am fairly new to the concept of TPL and async/wait, I'm having some trouble explaining the behavior I am seeing here. Is there some sort of limitations in the Async CTP that kicks in, that I am not aware of, or am I doing this in a conceptually wrong way?

As a general rule, synchronous wrappers around asynchronous methods are strongly discouraged. When you use the Result approach, you run the risk of deadlock (as I describe on my blog); also, Result will wrap any exceptions, which makes your error handling much trickier.
So I'd say "don't do that."
As far as the Async CTP goes, there are a number of bugs that are known to exist (plus several more that are not public). And they're not going to be fixed. I strongly recommend upgrading everyone to VS2012.
For this particular issue, it may be performance-related. E.g., Task.Delay(1) returns a task that will complete almost immediately, so there's a race condition between starting the delay and the await which checks whether the task is already complete. So it's possible that performance improvements in the official Microsoft.Bcl.Async are causing the difference in behavior.

Related

Code injection thorugh Visual Studio 2015, How to remove code for security

I used to develop code injection programs with Visual Studio 2010 (maybe 5 years ago?).
Now I need it again and I developed it pretty much the same as before (with Visual Studio 2015).
However, I have confirmed that the codes I have not seen before are generated.
The first thing I found is the above problem.
It seems that the program's entry point, the address of the function, uses the table without pointing directly to the contents.
The problem is that I can not find the address and size of the injected code.
Is there a way to disable it?
The second problem is that weird functions are added.
My injection code is code that calls CreateProcess, ExitProcess.
However, each address is called immediately after each function is called.
This is the part of 0x013A14CE : CALL test.013A1DA0 above.
The contents of the function are as above.
This problem causes a crash after injecting the code.
I do not know what this is doing, but I think it's code for security.
I found several compile options, but I could not solve the problem.
I tried to compile with Visual Studio 2010, but the result was the same.
Inline assembly seems to be able to solve this problem, but it seems hard to solve it every time there is a fix.
please answer my question

Realm query doesn't work in Release mode in Xamarin

The following query works in Debug mode only:
private IQueryable<UserState> UsersOfEmail(string email)
{
return this.realm.All<UserState>()
.Where(u => u.EmailAddress == email);
}
When in Release mode, I get the error:
The rhs of the binary operator 'Equal' should be a constant or closure variable expression
I found a workaround for the error, but it doesn't seem to apply here.
When I check the Enable debugging option for the project (iOS, in this case), it works fine, which is why it was working in Debug mode only in the first place.
Any clue on the relationship between the error and the debugging option?
UPDATE
After further investigation, I found out that this issue has no relation to Realm.
I was misusing the event pub-sub feature of Prism (MVVM framework, among other things), and subscribing multiple times to an event in a view model of a page that would be navigated to and from, without unsubscribing in each interaction.
I thought this was a Realm issue because I didn't realize at first that the email parameter was null when in Release mode.
By using the pub-sub correctly, I was able to mitigate the problem. I still don't have an answer as to why it was only happening in Release mode, even though the Linking option was disabled in both build modes.
​We have a new release coming out soon which uses relinq to handle expression parsing and should dramatically improve how we handle linq, especially for this kind of expression.
It will be the next release after 0.77.2.
However, you are the first to identify something failing only in a Release mode so there may be something more complex going on.
Is there any difference in the Linking settings between your simple and complex apps? Maybe linker stripping is causing some problems.

ShimNotImplementedException after upgrading Visual Studio 2013 and Microsoft Fakes v12

We are utilizing Microsoft Fakes with Visual Studio 2013. After updating to Visual Studio 2013 Update-4 or Update-5, we are getting ShimNotImplementedException's in our tests.
We have followed instructions found in other SOF questions and turned off the SpecificVersion of our Microsoft.QualityTools.Testing.Fakes references. This allows a compile but the tests still fail when run.
The hint we needed to solve this was found in MSDN forums.
The underlying issue is that the legacy tests did not define specific methods
on the ShimXXX object that the code based is using. Under version 11
all is well; version 12 is a different matter.
The stack trace for the ShimNotImplementedException gave the needed information on the missing property/method:
Microsoft.QualityTools.Testing.Fakes.Shims.ShimNotImplementedException
at $Func`2NotImplementedf5b9281e-32b0-4bf3-9079-6a54470670de.Invoke(SiteContext arg1)
at Sitecore.Sites.SiteContext.get_Database() //THIS IS THE PROBLEM PROPERTY
at Sitecore.Ecommerce.ShopContext..ctor(SiteContext innerSite)
at ActiveCommerce.UnitTest.ProductStockManagerTests.get_MockShopContext()
at ActiveCommerce.UnitTest.ProductStockManagerTests.GetAvailability_AlwaysInStock()
Adding the missing property to our shim construction solved the issue:
return new Sitecore.Ecommerce.ShopContext(new ShimSiteContext
{
PropertiesGet = () => new NameValueCollection(),
DatabaseGet = () => null //ADDING THIS SOLVED THE ISSUE
});
I ran in to a similar problem after upgrading several of our projects from .NET 4 to .NET 4.5.2 using Visual Studio 2015. All the sudden several previously passing tests started failing. The common denominator was that all of the tests were using Shims to mock registry access.
What appears to have happened is that something changed in the handling of the Dispose method. Originally I had not implemented a Dispose method on the RegistryKey shims. That didn't seem to cause any trouble running under .NET 4. However after the switch to 4.5.2, it is implicitly being called all the time.
The solution was simple: I just added a stub for Dispose.
Microsoft.Win32.Fakes.ShimRegistryKey.AllInstances.Dispose = (key) => { };
The tests now pass again.
Note that setting it to NULL did not solve it for it. There has to be a method.

MSBuild doesn't find async required references

We have Visual Studio 2010 SP1 and Async CTP (SP1 refresh) installed.
A solution with projects that use async/await keywords builds OK when build from VS IDE.
Also when built with devenv /build "Debug" solution.sln everything is OK.
However msbuild #commands.rsp solution.sln reports:
File.xaml.cs(123): error CS1993: Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?
commands.rsp looks like this:
/nologo
/p:Configuration=Debug
/m:3
/fileLogger
Any clues?
Please, refer to the discussion here: http://social.msdn.microsoft.com/Forums/uk-UA/async/thread/3d491cb0-a19f-4faf-80a6-5fd05e4e06db
There are 2 points to be clarified in order to understand better your problem:
Environment: did you install VS11 side-by-side with VS 2010+Async CTP?
Your project: do you have XAML with user controls and "clr-namespace" in your project?
I will cite the preliminary conclusion by SERware from the discussion on the MS forum:
I think it has to do with the order in which the XAML projects
compile assemblies when referring to classes of the library itself. In
this case, the XAML Loader try to compile this classes before having
reference to the Async CTP library. So, the keyword "async" is not
recognized.
Personally I am going to see whether it is possible to split the assembly in order to resolve the order of the compilation of the dependencies in XAML
Added after further investigation:
As I have found out, the explanation is even more disappointing: the .NET 4.5 (Beta) replaces the .NET 4.0. Besides, the signatures of the async/wait related types have been internally changed. Therefore there is no way so far to use simultaneously VS 2010+AsyncATP and VS11 Beta. – Yuri S. 2 mins ago
I was hit by this myself and for various reasons I can't upgrade the projects to .NET 4.5 so I had to develop a workaround.
Since this is only a problem for XAML projects that has a xmlns declaration pointing to itself I'm able to use async on all the other projects that are referenced. This means my architecture is still utilizing async/await and is prepared for the move to .NET 4.5 later.
But in the affected XAML projects, I just manually implement (poorly) the await things otherwise done by the compiler.
So code that was this clean before:
try
{
var foo = GetFoo();
foo.DoStuff();
var data = await foo.GetDataAsync();
bar.WorkOnData(data);
}
catch (Exception ex)
{
// Logging, throw up a popup, whatever...
HandleError("Failed to get data", ex);
}
Now becomes this:
var foo = GetFoo();
foo.DoStuff();
var getDataTask = foo.GetDataAsync();
getDataTask.ContinueWith(t =>
{
if (t.IsFaulted)
{
// Logging, throw up a popup, whatever...
HandleError("Failed to get data", t.Exception);
return;
}
if (t.Status == TaskStatus.RanToCompletion)
{
bar.WorkOnData(t.Result);
}
});
Not ideal of course, and this is the exact thing that async/await was created to solve. But it does work as a short-term workaround at least for simple uses of await.

visual studio 2010 debugger - steps into an "if" statement despite condition false

I'm using VS 2010 Professional (On Windows 7 Professional 64), writing with WCF 4.0.
I have the following code:
if (responseMessage.StatusCode == HttpStatusCode.NotFound)
{
throw new ContentNotFoundException(contentId, SSPErrorCode.PartnerRestGetStream404);
}
When attaching the debugger to the process, having set a breakpoint at the "if" statement or before that, while the condition is false (responseMessage.StatusCode is 'OK'), the debugger steps into the "if" statement. It then steps over the "throw" statement without doing anything, then continuing on with the code.
I've tried:
Restarting VS, logging out my Windows user, rebooting, cleaning the solution, building it again, rebuilding it, recycling the application pool, resarting IIS, adding more code inside the "if" statement and inside the condition - nothing worked so far.
There must be a cache somewhere which I can clean to get rid of it, but what, and where?
Googling this I only found http:--social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/d4b70fd7-b74a-42ce-a538-7185df3d3254/, so I tried manually setting the breakpoint, and it didn't break in this class, although the same did break in other classes.
I would love to fix this without reinstalling VS. Thank you in advance!
Update:
Since I put this up and could not find an answer, I moved on with my project.
I stumbled upon this issue, reported by John MacIntyre on this post, which ends up with a simplified example:
using System;
namespace IEnumerableBug2
{
class Program
{
static void Main(string[] args)
{
if (new object() == null)
throw new Exception();
try { } catch { }
}
}
}
Update #2:
Note that my Method also has a try-catch statement in it, a few lines after the 'if' statement.
I've just tried reproducing this bug again, and failed. I'm going to leave the question on stackoverflow for others who might need it, but, as I wrote, I am no longer able to reproduce the behaviour.
I am experiencing this problem too, but slightly different.
Here's my code:
string lockCode = Guid.NewGuid().ToString();
bool alreadyLocked = string.IsNullOrWhiteSpace(lockCode);
if (alreadyLocked) {
throw new Exception("already running");
}
try {
PerformTask(task);
}
finally {
UnlockTask(task, lockCode);
}
As you can see, the lockCode string is always assigned with a Guid value. The debugger steps into the 'if' scope, although it shouldn't. The exception isn't thrown.
I am running Visual Studio 2010 SP1 on Windows 7 64-bit with ReSharper 6.0.
Microsoft Visual Studio 2010
Version 10.0.40219.1 SP1Rel
Microsoft .NET Framework
Version 4.0.30319 SP1Rel
Installed Version: Premium
This happens to me with an ASP.NET application on framework 4.0.
I tried running the repro code posted here on a different project on my machine but could not reproduce the issue.
Also, I have deleted the Shadow Copy Cache for the .NET Framework on this path:
C:\Users\username\AppData\Local\assembly
I deleted the VS2010 symbols cache directory, and the Temporary ASP.NET Files.
I restarted my computer, cleaned the whole solution and rebuilt everything.
No clue why this happens.
Workaround: If I remove the 'try-finally' part from the method, or extract the throw statement to a different method, the debugger steps over the 'if' scope correctly.
Sorry for not posting a real solution to this, I hope this helps either isolate the problem or work around it.
Today I also experienced this issue. The following code solves the problem, with the advantage of not compiling the workaround on release builds:
using System;
namespace IEnumerableBug2
{
class Program
{
static void Main(string[] args)
{
if (new object() == null)
throw new Exception();
#if DEBUG
bool workaround = true; // dummy instruction
#endif
try { } catch { }
}
}
}
While stranger things have in fact happened, I highly doubt that this is a bug in the debugger or bad bad VS installation.
I think something must be happening that you're not interperting correctly. Did you put the expression "responseMessage.StatusCode == HttpStatusCode.NotFound" into the Debug Watch window? What does it return? Is it possible StatusCode is returning a different value each time? Did you try evaluating it several times to make sure it is consistent?
The only way I could imagine this happening is if the code was changed, and when prompted whether or not you want to debug the source file even though its version does not match, you answered Yes. This would explain why you can skip over the "throw" line without it doing anything - you're not debugging the actual code you're seeing, but an older version of it. To fix this, rebuild everything, and never say yes when prompted if you want to debug even though there is a version mismatch - it is way too confusing!

Resources