Created
December 22, 2016 23:09
-
-
Save antonfirsov/3885036fee86e2fd97f486ab88541dc7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Numerics; | |
using System.Runtime.InteropServices; | |
using System.Threading.Tasks; | |
namespace AsyncMeetsUnsafe | |
{ | |
[StructLayout(LayoutKind.Sequential)] | |
public class LocalityCriticalData : IDisposable | |
{ | |
public Matrix4x4 Block1; | |
public Matrix4x4 Block2; | |
public GCHandle Handle; | |
public IntPtr BasePtr; | |
public unsafe Matrix4x4* Block1Ptr; | |
public unsafe Matrix4x4* Block2Ptr; | |
public unsafe LocalityCriticalData() | |
{ | |
Block1 = Matrix4x4.CreateScale(1, 2, 3); | |
Block2 = Matrix4x4.CreateScale(4, 5, 6); | |
Handle = GCHandle.Alloc(this, GCHandleType.Pinned); | |
BasePtr = Handle.AddrOfPinnedObject(); | |
Block1Ptr = (Matrix4x4*) (float*) BasePtr; | |
Block2Ptr = Block1Ptr + 1; | |
} | |
public unsafe float GetBlock1Element(int idx) | |
{ | |
float* p = (float*) Block1Ptr + idx; | |
return *p; | |
} | |
public unsafe float GetBlock2Element(int idx) | |
{ | |
float* p = (float*)Block2Ptr+idx; | |
return *p; | |
} | |
public async Task<float> CalculateStuff() | |
{ | |
float a = GetBlock1Element(5); | |
float b = await RecieveDataFromMars(); | |
float c = GetBlock2Element(5); | |
return a + b + c; | |
} | |
private async Task<float> RecieveDataFromMars() | |
{ | |
await Task.Delay(100); | |
return 4.8f; | |
} | |
public void Dispose() | |
{ | |
Handle.Free(); | |
} | |
} | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
DoWorkAsync().Wait(); | |
} | |
private static async Task DoWorkAsync() | |
{ | |
using (var data = new LocalityCriticalData()) | |
{ | |
Assert.Equal(data.GetBlock1Element(0), 1); | |
Assert.Equal(data.GetBlock2Element(0), 4); | |
float result = await data.CalculateStuff(); | |
float expected = 2 + 4.8f + 5; | |
Assert.Equal(result, expected); | |
} | |
Console.ReadLine(); | |
} | |
} | |
static class Assert | |
{ | |
public static void Equal<T>(T a, T b) | |
{ | |
if (!a.Equals(b)) throw new Exception("Assertion failed!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment