how to implement async method using Task Parallel Library for I/O operations - parallel-processing

I found that for expensive IO bound operation I can use TaskCompletionSource
as shown here http://msdn.microsoft.com/en-us/library/hh873177.aspx#workloads
But the example shown is only waiting for some time and return DateTime.
public static Task<DateTimeOffset> Delay(int millisecondsTimeout)
{
TaskCompletionSource<DateTimeOffset> tcs = null;
Timer timer = null;
timer = new Timer(delegate
{
timer.Dispose();
tcs.TrySetResult(DateTimeOffset.UtcNow);
}, null, Timeout.Infinite, Timeout.Infinite);
tcs = new TaskCompletionSource<DateTimeOffset>(timer);
timer.Change(millisecondsTimeout, Timeout.Infinite);
return tcs.Task;
}
Above code waits for timeout. I have a database call which I want to fire in the above way, but little confused in how to write it:
using (var context = new srdb_sr2_context())
{
return context.GetData("100", "a2acfid");
}
I wrote the function as below, but not sure if this is correct way of doing it:
TaskCompletionSource<IList<InstructorsOut>> tcs = null;
Timer timer = null;
timer = new Timer(delegate
{
timer.Dispose();
//prepare for expensive data call
using (var context = new srdb_sr2_context())
{
var output = context.GetData("100", "a2acfid");
//set the result
tcs.TrySetResult(output);
}
}, null, Timeout.Infinite, Timeout.Infinite);
tcs = new TaskCompletionSource<IList<InstructorsOut>>(timer);
timer.Change(0, Timeout.Infinite);
return tcs.Task;
Any help would be appreciated.

Your code doesn't make much sense to me. Timer is useful if you want to execute the code after some time, but that's not what you need here.
If you want to execute an operation on a background thread, you can use Task.Run():
Task<IList<InstructorsOut>> GetDataBackground()
{
return Task.Run(() =>
{
using (var context = new srdb_sr2_context())
{
return context.GetData("100", "a2acfid");
}
});
}
Using a background thread this way can be useful in UI apps, where you don't want to block the UI thread. But if you have something like ASP.NET application, this won't actually give you any performance or scalability improvements. For that, the GetData() method would have to be made truly asynchronous.

Related

Windows 8.1 store apps OnCommandsRequested doesn't add ApplicationCommands when async used

On the App.xaml.cs I have the following code
private async void OnCommandsRequested(SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs e)
{
var loader = ResourceLoader.GetForCurrentView();
var generalCommand = new SettingsCommand("General Settings", "General Settings", handler =>
{
var generalSettings = new GeneralSettingsFlyout();
generalSettings.Show();
});
e.Request.ApplicationCommands.Add(generalCommand);
object data;
IAuthService _authService = new AuthService();
if (Global.UserId == 0)
data = await _authService.GetSettingValueBySettingName(DatabaseType.GeneralDb, ApplicationConstants.GeneralDbSettingNames.ShowSupportInfo);
else
data = await _authService.GetSettingValueBySettingName(DatabaseType.UserDb, ApplicationConstants.UserDbSettingNames.ShowSupportInfo);
if (data != null && data.ToString().Equals("1"))
{
var supportCommand = new SettingsCommand("Support", "Support", handler =>
{
var supportPane = new SupportFlyout();
supportPane.Show();
});
e.Request.ApplicationCommands.Add(supportCommand);
}
var aboutCommand = new SettingsCommand("About", loader.GetString("Settings_OptionLabels_About"), handler =>
{
var aboutPane = new About();
aboutPane.Show();
});
e.Request.ApplicationCommands.Add(aboutCommand);
}
This code adds the setting "General Settings" but neither "Support" or "About" commands. Can anyone advice what's wrong with this code?
Instead of querying the commands from your service when they are requested you'll need to query them ahead of time and then add the already known commands.
You cannot use await in OnCommandsRequested.
A method returns when it gets to the first await, so only commands added to the request before the await will be used.
Since the SettingsPaneCommandsRequestedEventArgs doesn't provide a deferral there is no way to tell the requester to wait for internal async calls to complete.
Note also that SettingsPane is deprecated and not recommended for new app development for Windows 10.

Xamarin.ios iphone device Current location(street address)

public static async Task<Position> GetCurrentLocation()
{
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100;
if (!locator.IsGeolocationAvailable)
throw new NotSupportedException("Geolocation not available");
if (!locator.IsGeolocationEnabled)
throw new GeolocationException(GeolocationError.PositionUnavailable);
return await locator.GetPositionAsync(timeoutMilliseconds: 100000);
}
catch (Exception ex)
{
//TODO: Add error logging
return null;
}
}
on return await locator.GetPositionAsync(timeoutMilliseconds: 100000);
the thread exit and debugger not return but the output window shows the location correctly but didn't return to the code. What should be the possible reason for this break?
If I understand your question, you would like to know why your async code behaves the way it does?
Let's first get the terminology right: there is no thread that exits. Async/await is not about threads but about orchestrating asynchronous operations.
Your code returns at the await if the Task you are waiting for has not completed yet. Later, execution will then be picked up after the awaited code. In your case, the only thing that will happen is that the result of the task (= the location) will be returned.
So in any case, your method will exit:
either because the task is not complete yet
or because it is complete and you are using return

How to read response data from nsIInputStream

I am trying to create a fire-bug like extension for firefox which is actually dev-tool extension. I have registered httpRequestObserver to observe http-on-examine-response event. I have a listener with below method implemented.
onDataAvailable: function(request, context, inputStream, offset, count) {
//I get the request URL using request.name
//What I need to do is fetch response data from inputStream
}
I have read the documentation here but still can't figure out.
I am looking for a way to read all the data from inputStream.
Let me know in case more details are required.
Thanks in advance.
I'm not a stream expert but this is some ways of doing things. I recommend Method 1 below, if you find problems with that, then go to Method 2, than if still problems, then research Method 3. Method 1 is definitely the most proper, as it follows contratcts agreement.
Method 1 - nsIScriptableScream read
Hold a global buffer and on start request blank it, and on data available populate it.
var ScriptableInputStream = CC("#mozilla.org/scriptableinputstream;1", "nsIScriptableInputStream", "init");
var blah = {
data: '',
onStartRequest: function (aRequest, aContext) {
this.data = '';
},
onDataAvailable: function(request, context, inputStream, offset, count) {
var scriptStream = new ScriptableInputStream(inputStream);
this.data += scriptStream.read(count);
scriptStream.close();
}
};
Method 2 - nsIBinaryInputStream readBytes
I don't know what advantage this readBytes method has, it might be that you can use this method for images as well, and the above method won't read images I'm not sure. This method also holds a global buffer and on start request blank it, and on data available populate it. Another advantage may be that you don't need to close a binary input stream, I'm not sure about this point though. I think it has no contract so you can reuse it.
var bstream = Cc["#mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);
var blah = {
data: '',
onStartRequest: function (aRequest, aContext) {
this.data = '';
},
onDataAvailable: function(request, context, inputStream, offset, count) {
bstream.setInputStream(inputStream);
var size = 0;
while(size = bstream.available()) {
this.data.value += bstream.readBytes(size);
}
}
};
Method 3 - this is another method i used in tracing listener
This method here I'm just copy pasting, as I don't understand it that well. I use it here though: GitHub :: Noitidart / demo-nsITraceableChannel #L120
function CCIN(cName, ifaceName) {
return Cc[cName].createInstance(Ci[ifaceName]);
}
TracingListener.prototype =
{
onDataAvailable: function(request, context, inputStream, offset, count)
{
var binaryInputStream = CCIN("#mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream");
var storageStream = CCIN("#mozilla.org/storagestream;1", "nsIStorageStream");
var binaryOutputStream = CCIN("#mozilla.org/binaryoutputstream;1",
"nsIBinaryOutputStream");
binaryInputStream.setInputStream(inputStream);
storageStream.init(8192, count, null);
binaryOutputStream.setOutputStream(storageStream.getOutputStream(0));
// Copy received data as they come.
var data = binaryInputStream.readBytes(count);
this.receivedData.push(data);
binaryOutputStream.writeBytes(data, count);
this.originalListener.onDataAvailable(request, context, storageStream.newInputStream(0), offset, count);

Unable to func-eval using Mdbg due to "code is optimized" exception

We are using MdbgCore.dll to evaluate a property off a parameter on a thread callstack.
To do this, we are performing a func-eval.
Unfortunately, all our attempts to perform the func-eval are failing with CORDBG_E_ILLEGAL_IN_OPTIMIZED_CODE, which seems to be due to the thread being used for the func-eval not being in a GC-safe point.
This is documented here: http://blogs.msdn.com/b/jmstall/archive/2005/11/15/funceval-rules.aspx.
We tried scanning all threads in the process to find a thread that is in a GC-safe point, but they all appear to have UserState marked with USER_UNSAFE_POINT.
There is very scarce documentation on the subject, and we are pulling our hair out trying to figure out if there is a way to get a thread in a GC-safe point so we can do the func-eval. We would consider anything that allows us to deterministically break into the process with a thread to do the func-eval with.
Disclaimer: we are trying to evaluate a method on a class that resides in an optimized assembly, so not sure if this is maybe also causing an issue.
The sample code follows:
if (argument.TypeName.EndsWith(
"WorkerRequest", StringComparison.OrdinalIgnoreCase)
&& !argument.IsNull)
{
try
{
// Invoke the "GetUriPath()" function to obtain the URI
string functionName = "System.Web.HttpWorkerRequest.GetUriPath";
MDbgFunction func = debugger.Processes.Active.ResolveFunctionNameFromScope(
functionName,
thread.CorThread.AppDomain
);
if (null == func)
{
throw new InvalidOperationException(
String.Format("Could not resolve {0}", functionName));
}
// Setup the eval
CorEval eval = threadForFuncEvals.CorThread.CreateEval();
// Setup the function parameters
List<CorValue> values = new List<CorValue>();
// Add the worker request "this" pointer
values.Add(
argument.CorValue
);
// resume the thread being used to do the func-eval
threadForFuncEvals.CorThread.DebugState = CorDebugThreadState.THREAD_RUN;
// Queue the function for execution
// EXCEPTION THROWN BELOW
// EXCEPTION THROWN BELOW
// EXCEPTION THROWN BELOW
eval.CallFunction(func.CorFunction, values.ToArray());
// BUGBUG: Should we pause all other threads to prevent them from moving?
// Continue the process to execute the function
if (!proc.Go().WaitOne(settings.BreakTimeout))
{
throw new InvalidOperationException("Timeout while evaluating function");
}
// get the returned string
var result = eval.Result;
if (result != null)
{
MDbgValue mv = new MDbgValue(proc, result);
string returnedValue = mv.GetStringValue(false);
threadInfo.Url = returnedValue;
}
}
catch (Exception e)
{
// BUGBUG: Ignoring exception
}
finally
{
// suspend the thread again
if (threadForFuncEvals != null)
{
threadForFuncEvals.CorThread.DebugState =
CorDebugThreadState.THREAD_SUSPEND;
}
}
}
Microsoft / Mdbg team, can you help?
Best,
Mike
Is this something to do with JIT optimization?
In my program, I turn JIT optimization off (for technical reasons, I think you can only do this with CreateProcess() and not using Attach()).
proc = m_Debugger.CreateProcess(ProcessName, ProcessArgs, DebugModeFlag.Default, DebugEngineUtils.GetAssemblyRuntimeVersion(ProcessName,DefaultNetVersion));
if (proc!=null) proc.CorProcess.OnCreateProcess += new Microsoft.Samples.Debugging.CorDebug.CorProcessEventHandler(CorProcess_OnCreateProcess);
if (proc!=null) proc.CorProcess.OnModuleLoad += new Microsoft.Samples.Debugging.CorDebug.CorModuleEventHandler(CorProcess_OnModuleLoad);
void CorProcess_OnModuleLoad(object sender, Microsoft.Samples.Debugging.CorDebug.CorModuleEventArgs e)
{
e.Module.JITCompilerFlags = Microsoft.Samples.Debugging.CorDebug.CorDebugJITCompilerFlags.CORDEBUG_JIT_DISABLE_OPTIMIZATION;
}
void CorProcess_OnCreateProcess(object sender, Microsoft.Samples.Debugging.CorDebug.CorProcessEventArgs e)
{
//try to disable optimization
((Microsoft.Samples.Debugging.CorDebug.CorProcess)sender).DesiredNGENCompilerFlags = Microsoft.Samples.Debugging.CorDebug.CorDebugJITCompilerFlags.CORDEBUG_JIT_DISABLE_OPTIMIZATION;
}

How to invoke async operation as sync?

I have a third party service which have async DoAsync() operation and Done() event. How can I create my own sync DoSync() operation?
I want smth like this (in pseudocode):
operation DoSync()
{
DoAsync();
wait until Done();
}
Try the AutoResetEvent http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx
One way to do this is to temporarily add an event handler, and in that handler, set some sort of waitable object. Here's an example that shows the technique with one of the async methods provided by WebClient
using System;
using System.Net;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
WebClient w = new WebClient();
using (var waiter = new ManualResetEventSlim())
{
DownloadDataCompletedEventHandler h = (sender, e) =>
{
if (e.Error != null)
{
Console.WriteLine(e.Error);
}
waiter.Set();
};
w.DownloadDataCompleted += h;
try
{
w.DownloadDataAsync(new Uri("http://www.interact-sw.co.uk/iangblog/"));
Console.WriteLine("Downloading");
waiter.Wait();
Console.WriteLine("Finished!");
}
finally
{
w.DownloadDataCompleted -= h;
}
}
}
}
}
Here's a simplified version that makes the basic technique easier to see, but which doesn't bother with things like error handling, or tidying up after itself:
WebClient w = new WebClient();
using (var waiter = new ManualResetEventSlim())
{
w.DownloadDataCompleted += delegate { waiter.Set(); };
w.DownloadDataAsync(new Uri("http://www.interact-sw.co.uk/iangblog/"));
Console.WriteLine("Downloading");
waiter.Wait();
Console.WriteLine("Finished!");
}
In most situations you will want to make sure you detect errors, and detach the handler when you're done - I just provided the shorter version to help illustrate the point. I wouldn't actually use that simplified one in a real program.

Resources