在以下代码中,如果取消注释“using static”行,查询将不会并行运行。为什么?
(Visual Studio 社区 2019,.Net Core 3.1 / .Net 4.8)
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace UsingStatic_Mystery
{
//using static Enumerable;
class Program
{
static void Main(string[] args)
{
var w = new Stopwatch();
iter:
w.Start();
var xx = Enumerable.Range(0, 10)
.AsParallel()
.OrderByDescending(x => {
Thread.Sleep(new Random().Next(100));
Console.WriteLine(x);
return x;
}).ToArray();
w.Stop();
Console.WriteLine();
foreach (var x in xx) Console.WriteLine(x);
Console.WriteLine(w.ElapsedMilliseconds);
Console.ReadLine();
w.Reset();
goto iter;
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出,未注释/注释:
我通过URI(Web或文件系统)获取图像,并希望将其编码为PNG并保存到临时文件:
var bin = new MemoryStream(raw).AsRandomAccessStream(); //raw is byte[]
var dec = await BitmapDecoder.CreateAsync(bin);
var pix = (await dec.GetPixelDataAsync()).DetachPixelData();
var res = new FileStream(Path.Combine(ApplicationData.Current.LocalFolder.Path, "tmp.png"), FileMode.Create);
var enc = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, res.AsRandomAccessStream());
enc.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, dec.PixelWidth, dec.PixelHeight, 96, 96, pix);
await enc.FlushAsync(); //hangs here
res.Dispose();
Run Code Online (Sandbox Code Playgroud)
问题是,这段代码挂起了await enc.FlushAsync().请帮忙!谢谢.
这里的大多数解决方案都使用System.Drawing,这在UWP afaik中是不可用的.GetThumbnailAsync()完成工作,但仅适用于非图像文件.使用图像文件,无论传递的参数如何,我都会获得缩放预览.
我想要一个shell文件图标,而不是文件名左边的小预览,如下所示:
有什么想法吗?
谢谢
PS:我发现了一个hack:创建一个具有相同扩展名的0字节临时文件并制作它的缩略图.我希望尽管有更好的解决方案......
在我的 UWP 应用程序中,我以字节 [] 的形式将图像存储在 SQLite 数据库中。然后,当我从数据库中检索我的对象时,我将它们绑定到具有 Image 控件的 GridView 数据模板。由于我无法将 Image 的 Source 直接绑定到数组,所以我在对象的类中创建了一个 BitmapImage 属性来将 Image 控件绑定到:
public BitmapImage Icon
{
get
{
using (var stream = new MemoryStream(icon))
{
stream.Seek(0, SeekOrigin.Begin);
var img = new BitmapImage();
img.SetSource(stream.AsRandomAccessStream());
return img;
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,我的应用程序挂在 img.SetSource 行上。经过一些试验,我发现这个问题可以用第二个 MemoryStream 来克服:
public BitmapImage Icon
{
get
{
using (var stream = new MemoryStream(icon))
{
stream.Seek(0, SeekOrigin.Begin);
var s2 = new MemoryStream();
stream.CopyTo(s2);
s2.Position = 0;
var img = new BitmapImage();
img.SetSource(s2.AsRandomAccessStream()); …Run Code Online (Sandbox Code Playgroud) 我刚刚发现一件奇怪的事情:
Action a1 = () => Console.Write("1 ");
Action a2 = () => Console.Write("2 ");
Action tmp = a1;
a1 += a2;
a2 = tmp;
Console.Write("a1:\t");
a1(); //a1: 1 2
Console.Write("\na2:\t");
a2(); //a2: 1
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
我预计这两个语句都会返回“1 2”;为什么不是这样呢?