Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 25 additions & 10 deletions docs/standard/memory-and-spans/memory-t-usage-guidelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,14 @@ class Program
static void Main()
{
var buffer = CreateBuffer();
try {
try
{
int value = Int32.Parse(Console.ReadLine());
WriteInt32ToBuffer(value, buffer);
DisplayBufferToConsole(buffer);
}
finally {
finally
{
buffer.Destroy();
}
}
Expand Down Expand Up @@ -146,9 +148,11 @@ But imagine instead that `Log` has this implementation.
static void Log(ReadOnlyMemory<char> message)
{
// Run in background so that we don't block the main thread while performing IO.
Task.Run(() => {
Task.Run(() =>
{
StreamWriter sw = File.AppendText(@".\input-numbers.dat");
sw.WriteLine(message); });
sw.WriteLine(message);
});
}
```

Expand Down Expand Up @@ -179,7 +183,8 @@ This guidance applies to methods that return <xref:System.Threading.Tasks.Task>,
Consider the following example:

```csharp
class OddValueExtractor {
class OddValueExtractor
{
public OddValueExtractor(ReadOnlyMemory<int> input);
public bool TryReadNextOddValue(out int value);
}
Expand Down Expand Up @@ -292,7 +297,8 @@ public unsafe Task<int> ManagedWrapperAsync(Memory<byte> data)
{
// setup
var tcs = new TaskCompletionSource<int>();
var state = new MyCompletedCallbackState {
var state = new MyCompletedCallbackState
{
Tcs = tcs
};
var pState = (IntPtr)GCHandle.Alloc(state;
Expand All @@ -302,9 +308,12 @@ public unsafe Task<int> ManagedWrapperAsync(Memory<byte> data)

// make the call
int result;
try {
try
{
result = ExportedAsyncMethod((byte*)memoryHandle.Pointer, data.Length, pState, _callbackPtr);
} catch {
}
catch
{
((GCHandle)pState).Free(); // cleanup since callback won't be invoked
memoryHandle.Dispose();
throw;
Expand All @@ -329,8 +338,14 @@ private static void MyCompletedCallbackImplementation(IntPtr state, int result)

/* error checking result goes here */

if (error) { actualState.Tcs.SetException(...); }
else { actualState.Tcs.SetResult(result); }
if (error)
{
actualState.Tcs.SetException(...);
}
else
{
actualState.Tcs.SetResult(result);
}
}

private static IntPtr GetCompletionCallbackPointer()
Expand Down