我正在观看异步的禅:最佳性能的最佳实践和Stephen Toub开始谈论任务缓存,而不是缓存任务作业的结果,你自己缓存任务.据我所知,为每项工作开始一项新任务是昂贵的,应该尽量减少.在28:00左右,他展示了这种方法:
private static ConcurrentDictionary<string, string> s_urlToContents;
public static async Task<string> GetContentsAsync(string url)
{
string contents;
if(!s_urlToContents.TryGetValue(url, out contents))
{
var response = new HttpClient().GetAsync(url);
contents = response.EnsureSuccessStatusCode().Content.ReadAsString();
s_urlToContents.TryAdd(url, contents);
}
return contents;
}
Run Code Online (Sandbox Code Playgroud)
首先看起来像是一个很好的思考方法,你缓存结果,我没有考虑缓存获取内容的工作.
而且他展示了这种方法:
private static ConcurrentDictionary<string, Task<string>> s_urlToContents;
public static Task<string> GetContentsAsync(string url)
{
Task<string> contents;
if(!s_urlToContents.TryGetValue(url, out contents))
{
contents = GetContentsAsync(url);
contents.ContinueWith(t => s_urlToContents.TryAdd(url, t); },
TaskContinuationOptions.OnlyOnRanToCompletion |
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
return contents;
}
private static async Task<string> GetContentsAsync(string url)
{ …Run Code Online (Sandbox Code Playgroud) 出于某种原因,当我从内存映射文件中读取几次它只是从内存中随机删除时,我不知道发生了什么.内核或GC是否从内存中删除它?如果是,我如何阻止他们这样做?
我正在将一个对象序列化为Json并将其写入内存.
几次尝试再读一次后,我得到一个例外,我得到了 FileNotFoundException: Unable to find the specified file.
private const String Protocol = @"Global\";
Run Code Online (Sandbox Code Playgroud)
public static Boolean WriteToMemoryFile<T>(List<T> data)
{
try
{
if (data == null)
{
throw new ArgumentNullException("Data cannot be null", "data");
}
var mapName = typeof(T).FullName.ToLower();
var mutexName = Protocol + typeof(T).FullName.ToLower();
var serializedData = JsonConvert.SerializeObject(data);
var capacity = serializedData.Length + 1;
var mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity);
var isMutexCreated = false;
var mutex = new Mutex(true, mutexName, out isMutexCreated);
if (!isMutexCreated)
{
var isMutexOpen …Run Code Online (Sandbox Code Playgroud) 我想以某种方式异步验证ABPadLockScreen中的引脚,因为引脚未保存在设备上.我正在使用Alamofire的http请求以及PromiseKit来承诺.
我试过用AwaitKit但问题是我遇到了僵局.
我也尝试过使用semaphore,但结果是一样的.由于我无法更改ABPadLock方法来容纳类似完成处理程序的东西,我需要一些解决方案,如果它阻塞主线程无关紧要,只是它有效.
Alamofire请求方法:
public func loginAsync(pinCode: String?, apiPath: String?) -> Promise<LoginResult>{
return Promise { fullfil, reject in
let params = [
"Pin": pinCode!
]
Alamofire.request(.POST, "\(baseUrl!)/\(apiPath!)", parameters: params).responseObject{(response: Response<LoginResult, NSError>) in
let serverResponse = response.response
if serverResponse!.statusCode != 200 {
reject(NSError(domain: "http", code: serverResponse!.statusCode, userInfo: nil))
}
if let loginResult = response.result.value {
fullfil(loginResult)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
ABPadLockScreen引脚验证方法:
public func padLockScreenViewController(padLockScreenViewController: ABPadLockScreenViewController!, validatePin pin: String!) -> Bool {
let pinCode = pin!
let defaults …Run Code Online (Sandbox Code Playgroud) 我想创建一个方法,扩展IQueryable用户可以在字符串中指定一个属性名称,用于区分集合.我想用一个逻辑HashSet.我基本上想模仿这段代码:
HashSet<TResult> set = new HashSet<TResult>();
foreach(var item in source)
{
var selectedValue = selector(item);
if (set.Add(selectedValue))
yield return item;
}
Run Code Online (Sandbox Code Playgroud)
使用表达式树.
这是我到目前为止的地方:
private Expression AssembleDistinctBlockExpression (IQueryable queryable, string propertyName)
{
var propInfo = queryable.ElementType.GetProperty(propertyName);
if ( propInfo == null )
throw new ArgumentException();
var loopVar = Expression.Parameter(queryable.ElementType, "");
var selectedValue = Expression.Variable(propInfo.PropertyType, "selectedValue");
var returnListType = typeof(List<>).MakeGenericType(queryable.ElementType);
var returnListVar = Expression.Variable(returnListType, "return");
var returnListAssign = Expression.Assign(returnListVar, Expression.Constant(Activator.CreateInstance(typeof(List<>).MakeGenericType(queryable.ElementType))));
var hashSetType = typeof(HashSet<>).MakeGenericType(propInfo.PropertyType);
var hashSetVar = Expression.Variable(hashSetType, …Run Code Online (Sandbox Code Playgroud) 我有一个通过SX Virtual Link连接到网络的KODAK i2600扫描仪,该网络在该网络中的每台PC上都模拟了与扫描仪的USB连接。我可以像这样轻松地找到仿真的USB pid和vid:

或这个: 
我尝试使用LibUsbDotNet来检测信号,但以他们的示例为例,它只是行不通。我尝试了以下示例:
public static UsbDevice MyUsbDevice;
#region SET YOUR USB Vendor and Product ID!
public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(int.Parse("040a", System.Globalization.NumberStyles.HexNumber), int.Parse("601d", System.Globalization.NumberStyles.HexNumber));
#endregion
public static void Main(string[] args)
{
ErrorCode ec = ErrorCode.None;
try
{
// Find and open the usb device.
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
// If the device is open and ready
if (MyUsbDevice == null) throw new Exception("Device Not Found.");
// If this is a "whole" usb device (libusb-win32, linux libusb-1.0) …Run Code Online (Sandbox Code Playgroud) 我有一个带有视图框的网格和一个路径.我希望网格鼠标悬停以更改路径的填充.但只有当直接在路径上时,鼠标才会触发it ignores the grid.
我查看了整个网络,但我找不到提到这个问题的任何地方.
XAML:
<Grid Grid.Column="0" Margin="15" x:Name="gdOpenBrowser">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter">
<i:InvokeCommandAction Command="{Binding OpenBrowserCursorCommand}"
CommandParameter="{Binding ElementName=gdOpenBrowser}"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction Command="{Binding LoginButtonCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Viewbox>
<Viewbox.RenderTransform>
<TranslateTransform X="-10" Y="-5"/>
</Viewbox.RenderTransform>
<Path Fill="White" Data="M38 8H10c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h8v-4h-8V16h28v20h-8v4h8c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM24 20l-8 8h6v12h4V28h6l-8-8z"/>
</Viewbox>
</Grid>
Run Code Online (Sandbox Code Playgroud)

我正在观看一个名为Becoming a C#Time Lord的视频,在0:35:36这个代码弹出:
async Task<TResult[]> PurelyWhenAll<TResult> (params Task<TResult>[] tasks)
{
var killJoy = new TaskCompletionSource<TResult[]>();
foreach ( var task in tasks )
task.ContinueWith(ant =>
{
if ( ant.IsCanceled )
killJoy.TrySetCanceled();
else if ( ant.IsFaulted )
killJoy.TrySetException(ant.Exception.InnerException);
});
return await await Task.WhenAny(killJoy.Task, Task.WhenAll(tasks));
}
Run Code Online (Sandbox Code Playgroud)
这是否意味着任务返回任务,因此我们有双重等待?如果我们有两个以上的等待,那么就性能会发生什么?这是一个好的做法吗,这应该避免吗?
这里发生了什么?这个循环大部分时间只是打印:
10101010101010101010
有时这样:
51010101010101010101
当我调试它时,它会按顺序打印
0123456789
class Program
{
static void Main (string[] args)
{
for ( int i = 0; i < 10; i++)
{
Task.Run(( ) => Console.Write(i));
}
Console.Read();
}
}
Run Code Online (Sandbox Code Playgroud) c# ×7
async-await ×2
task ×2
.net ×1
alamofire ×1
asynchronous ×1
caching ×1
ios ×1
libusbdotnet ×1
linq ×1
memory ×1
mutex ×1
swift ×1
wpf ×1