知乎周源微信_每周源代码56-Visual Studio 2010和.NET Framework 4培训套件-代码合同,并行框架和COM互操作...

本文介绍了.NET Framework 4 Training Kit中的亮点,包括代码合同、并行扩展和COM互操作的改进。代码合同提供了方法级别的契约,增强了代码的可靠性;并行扩展通过Parallel.ForEach简化了多核处理器的并行任务执行,显著提升了性能;而COM互操作在.NET 4中变得更加简单。这些内容适合用于学习和教学,帮助开发者更好地理解和利用.NET 4的新特性。
摘要由CSDN通过智能技术生成
知乎周源微信

知乎周源微信

Do you like a big pile of source code? Well, there is an imperial buttload of source in the Visual Studio 2010 and .NET Framework 4 Training Kit. It's actually a 178 meg download, which is insane. Perhaps start your download now and get it in the morning when you get up. It's extremely well put together and I say Kudos to the folks that did it. They are better people than I.

您喜欢一大堆源代码吗? 好吧, Visual Studio 2010和.NET Framework 4 Training Kit中大量的源代码。 实际上,这是一次178兆的下载,太疯狂了。 也许现在就开始下载,并在早晨起床时下载。 放在一起非常好,我向做到这一点的人说荣誉。 他们是比我更好的人。

I like to explore it while watching TV myself and found myself looking through tonight. I checked my blog and while I thought I'd shared this with you before, Dear Reader, I hadn't. My bad, because it's pure gold. With C# and VB, natch.

我喜欢一边看电视一边探索它,发现自己今晚一直在看。 我检查了我的博客,而我以为曾经与您分享过此内容,亲爱的读者,我没有。 不好,因为它是纯金的。 使用C#和VB,natch。

Here's an outline of what's inside. I've heard of folks setting up lunch-time study groups and going through each section.

这是里面的概要。 我听说有人建立午餐时间学习小组并遍历每个部分。

C# 4Visual Basic 10 
F# Parallel Extensions
Windows Communication Foundation Windows Workflow
Windows Presentation Foundation ASP.NET 4
Windows 7 Entity Framework
ADO.NET Data Services (OData) Managed Extensibility Framework
Visual Studio Team System RIA Services
Office Development 
C#4 Visual Basic 10
F# 并行扩展
Windows Communication Foundation Windows工作流程
Windows Presentation Foundation ASP.NET 4
Windows 7的 实体框架
ADO.NET数据服务(OData) 托管扩展框架
Visual Studio团队系统RIA服务
办公室发展

I love using this kit in my talks, and used it a lot in my Lap Around .NET 4 talk.

我喜欢在我的演讲中使用这个工具包,并且在我的Lap Around .NET 4演讲中经常使用它。

There's Labs, Presentations, Demos, Labs and links to online Videos. It'll walk you step by step through loads of content and is a great starter if you're getting into what's new in .NET 4.

有实验室,演示文稿,演示,实验室以及指向在线视频的链接。 它会逐步引导您完成内容的加载,如果您了解.NET 4的新增功能,那么它将是一个很好的入门。

Here's a few of my favorite bits, and they aren't the parts you hear the marketing folks gabbing about.

这是我最喜欢的一些内容,而这些并不是您听到的营销人员的嘲笑声。

代码合同 (Code Contracts)

Remember the old coding adage to "Assert Your Expectations?" Well, sometimes Debug.Assert is either inappropriate or cumbersome and what you really need is a method contract. Methods have names and parameters, and those are contracts. Now they can have conditions like "don't even bother calling this method unless userId is greater than or equal to 0 and make sure the result isn't null!

还记得“确认您的期望”的古老编码格言吗? 好吧,有时Debug.Assert要么不合适,要么麻烦,您真正需要的是方法合同。 方法具有名称和参数,而这些则是合同。 现在,它们可以具有类似条件,例如“除非userId大于或等于0并确保结果不为null,否则不要再调用此方法!

Code Contracts continues to be revised, with a new version out just last month for both 2008 and 2010. The core types that you need are included in mscorlib with .NET 4.0, but you do need to download the tools to see them inside Visual Studio. If you have VS Pro, you'll get runtime checking and VS Ultimate gets that plus static checking. If I have static checking and the tools I'll see a nice new tab in Project Properties:

代码合同继续得到修订,上个月同时发布了2008和2010的新版本。所需的核心类型包含在.NET 4.0的mscorlib中,但是您确实需要下载工具才能在Visual Studio中查看它们。 如果您拥有VS Pro,则将获得运行时检查,而VS Ultimate将获得运行检查和静态检查。 如果我有静态检查和工具,我将在“项目属性”中看到一个漂亮的新标签:

I can even get Blue Squigglies for Contract Violations as seen below.

我什至可以看到违反合同的“蓝色弯曲”,如下所示。

A blue squigglie showing that a contract isn't satisfied

As a nice coincidence, you can go and download Chapter 15 of Jon Skeet's C# in Depth for free which happens to be on Code Contracts.

巧合的是,您可以免费下载Depth中Jon Skeet C#的第15章,该章恰巧是代码合同上的内容。

Here's a basic idea of what it looks like. If you have static analysis, you'll get squiggles on the lines I've highlighted as they are points where the Contract isn't being fulfilled. Otherwise you'll get a runtime ContractException. Code Contracts are a great tool when used in conjunction with Test Driven Development.

这是它的外观的基本概念。 如果您有静态分析,您会在我突出显示的行上出现花样,因为它们是未履行合同的点。 否则,您将获得运行时ContractException。 当与测试驱动开发一起使用时,代码合同是一个很好的工具。

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics.Contracts;

namespace ContractsDemo
{
[ContractVerification(true)]
class Program
{
static void Main(string[] args)
{
var password = GetPassword(-1);
Console.WriteLine(password.Length);
Console.ReadKey();
}

#region Header
/// <param name="userId">Should be greater than 0</param>
/// <returns>non-null string</returns>
#endregion
static string GetPassword(int userId)
{
Contract.Requires(userId >= 0, "UserId must be");
Contract.Ensures(Contract.Result<string>() != null);

if (userId == 0)
{
// Made some code to log behavior

// User doesn't exist
return null;
}
else if (userId > 0)
{
return "Password";
}

return null;
}
}
}

COM Interop在.NET 4中的功能更少 (COM Interop sucks WAY less in .NET 4)

I did a lot of COM Interop back in the day and it sucked. It wasn't fun and you always felt when you were leaving managed code and entering COM. You'd have to use Primary Interop Assemblies or PIAs and they were, well, PIAs. I talked about this a little bit last year in Beta 1, but it changed and got simpler in .NET 4 release.

那天我做了很多COM Interop,结果很糟糕。 这不好玩,当您离开托管代码并进入COM时,您总会感觉到。 您必须使用主要互操作程序集或PIA,而它们是PIA去年,我在Beta 1中谈到了这一点,但是它发生了变化,并且在.NET 4版本中变得更加简单。

Here's a nice little sample I use from the kit that gets the Processes on your system and then makes a list with LINQ of the big ones, makes a chart in Excel, then pastes the chart into Word.

这是我从工具包中使用的一个不错的小样本,该样本可以在您的系统上获取“进程”,然后列出LINQ中的大型进程,在Excel中创建图表,然后将图表粘贴到Word中。

If you've used Office Automation from managed code before, notice that you can say Range[] now, and not get_range(). You can call COM methods like ChartWizard with named parameters, and without including Type.Missing fifteen times. As an aside, notice also the default parameter value on the method.

如果以前使用过托管代码中的Office Automation,请注意,您现在可以说Range [],而不是get_range()。 您可以使用命名参数来调用ChartWizard之类的COM方法,而无需包含Type.Missing十五次。 顺便提一句,还要注意方法的默认参数值。

static void GenerateChart(bool copyToWord = false)
{
var excel = new Excel.Application();
excel.Visible = true;
excel.Workbooks.Add();

excel.Range["A1"].Value2 = "Process Name";
excel.Range["B1"].Value2 = "Memory Usage";

var processes = Process.GetProcesses()
.OrderByDescending(p => p.WorkingSet64)
.Take(10);
int i = 2;
foreach (var p in processes)
{
excel.Range["A" + i].Value2 = p.ProcessName;
excel.Range["B" + i].Value2 = p.WorkingSet64;
i++;
}

Excel.Range range = excel.Range["A1"];
Excel.Chart chart = (Excel.Chart)excel.ActiveWorkbook.Charts.Add(
After: excel.ActiveSheet);

chart.ChartWizard(Source: range.CurrentRegion,
Title: "Memory Usage in " + Environment.MachineName);

chart.ChartStyle = 45;
chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
Excel.XlCopyPictureFormat.xlBitmap,
Excel.XlPictureAppearance.xlScreen);

if (copyToWord)
{
var word = new Word.Application();
word.Visible = true;
word.Documents.Add();

word.Selection.Paste();
}
}

You can also embed your PIAs in your assemblies rather than carrying them around and the runtime will use Type Equivalence to figure out that your embedded types are the same types it needs and it'll just work. One less thing to deploy.

您也可以将PIA嵌入到程序集中,而不是随身携带它们,运行时将使用类型等效性来确定您的嵌入式类型与所需的类型相同,并且可以正常工作。 少部署一件事。

并行扩展 (Parallel Extensions )

The #1 reason, IMHO, to look at .NET 4 is the parallelism. I say this not as a Microsoft Shill, but rather as a dude who owns a 6-core (12 with hyper-threading) processor. My most favorite app in the Training Kit is ContosoAutomotive. It's a little WPF app that loads a few hundred thousand cars into a grid. There's an interface, ICarQuery, that a bunch of plugins implement, and the app foreach's over the CarQueries.

恕我直言,看.NET 4的第一原因是并行性。 我说这不是作为Microsoft Shill,而是作为拥有6核(带有超线程的12核)处理器的家伙。 培训套件中最喜欢的应用程序是ContosoAutomotive。 这是一个小的WPF应用程序,可将数十万辆汽车加载到网格中。 有一个接口ICarQuery,由一堆插件实现,并且foreach的应用程序都在CarQueries上。

This snippet here uses the new System.Threading.Task stuff and makes a background task. That's all one line there, from StartNew() all the way to the bottom. It says, "do this chunk in the background." and it's a wonderfully natural and fluent interface. It also keeps your UI thread painting so your app doesn't freeze up with that "curtain of not responding" that one sees all the time.

这里的代码片段使用了新的System.Threading.Task材质并创建了一个后台任务。 从StartNew()一直到底部,这就是一行。 它说:“在后台执行此块。” 这是一个非常自然和流畅的界面。 它还可以保持UI线程的绘制状态,以便您的应用程序不会一直被人们一直看到的“不响应的窗帘”冻结。

private void RunQueries()
{
this.DisableSearch();
Task.Factory.StartNew(() =>
{
this.BeginTiming();
foreach (var query in this.CarQueries)
{
if (this.searchOperation.Token.IsCancellationRequested)
{
return;
}

query.Run(this.cars, true);
};
this.EndSequentialTiming();
}, this.searchOperation.Token).ContinueWith(_ => this.EnableSearch());
}

StartNew() also has a cancellation token that we check, in case someone clicked Cancel midway through, and there's a ContinueWith at the end that re-enables or disabled Search button.

如果有人在途中单击“取消”,StartNew()还有一个取消标记,我们会检查该标记,最后还有一个ContinueWith可以重新启用或禁用“搜索”按钮。

Here's my system with the queries running. This is all in memory, generating and querying random cars.

这是运行查询的我的系统。 这些全部存储在内存中,生成和查询随机汽车。

And the app says it took 2.3 seconds. OK, what if I do this in parallel, using all the processors?

该应用程序说,这花了2.3秒。 好的,如果我使用所有处理器并行执行此操作,该怎么办?

Here's the changed code. Now we have a Parallel.ForEach instead. Mostly looks the same.

这是更改后的代码。 现在我们有了一个Parallel.ForEach。 大部分看起来都一样。

private void RunQueriesInParallel()
{
this.DisableSearch();
Task.Factory.StartNew(() =>
{
try
{
this.BeginTiming();
var options = new ParallelOptions() { CancellationToken = this.searchOperation.Token };
Parallel.ForEach(this.CarQueries, options, (query) =>
{
query.Run(this.cars, true);
});
this.EndParallelTiming();
}
catch (OperationCanceledException) { /* Do nothing as we cancelled it */ }
}, this.searchOperation.Token).ContinueWith(_ => this.EnableSearch());
}

This code says "go do this in a background thread, and while you're there, parallelize this as you like." This loop is "embarrassingly parallel." It's a big for loop over 2 million cars in memory. No reason it can't be broken apart and made faster.

这段代码说:“在后台线程中执行此操作,然后在您需要的时候将其并行化。” 这个循环是“令人尴尬的并行”。 这对于循环存储超过200万辆汽车而言意义重大。 没有理由不能将其分解和提高速度。

Here's the deal, though. It was SO fast, that Task Manager didn't update fast enough to show the work. The work was too easy. You can see it used more CPU and that there was a spike of load across 10 of the 12, but the work wasn't enough to peg the processors.

不过,这是交易。 太快了,任务管理器的更新速度不足以显示工作。 工作太简单了。 您可以看到它使用了更多的CPU,并且在12个处理器中有10个出现了峰值负载,但是工作还不足以固定处理器。

 

Did it even make a difference? Seems it was 5x faster and went from 2.389s to 0.4699 seconds. That's embarrassingly parallel. The team likes to call that "delightfully parallel" but I prefer "you're-an-idiot-for-not-doing-this-in-parallel parallel," but that was rejected.

它甚至有所作为吗? 似乎速度提高了5倍,从2.389秒缩短至0.4699秒。 这令人尴尬地是并行的。 团队喜欢将其称为“令人愉快的并行”,但我更喜欢“你是个白痴,不做这种并行的并行”,但是被拒绝了。

Let's try something harder. How about a large analysis of Baby Names. How many Roberts born in the state of Washington over a 40 year period from a 500MB database?

让我们再努力一点。 如何对婴儿名字进行大量分析。 在500年的数据库中,有40年来在华盛顿州出生的罗伯茨有多少人?

Here's the normal single-threaded foreach version in Task Manager:

这是任务管理器中的普通单线程foreach版本:

Here's the parallel version using 96% CPU.

这是使用96%CPU的并行版本。

And here's the timing. Looks like the difference between 20 seconds and under 4 seconds.

这是时候了。 看起来介于20秒和4秒之间。

You can try this yourself. Notice the processor slider bar there at the bottom.

您可以自己尝试。 请注意底部的处理器滑杆。

ProcessorsToUse.Minimum = 1;
ProcessorsToUse.Maximum = Environment.ProcessorCount;
ProcessorsToUse.Value = Environment.ProcessorCount; // Use all processors.

This sample uses "Parallel LINQ" and here's the two queries. Notice the "WithDegreeofParallelism."

本示例使用“ Parallel LINQ”,这是两个查询。 请注意“ WithDegreeofParallelism”。

seqQuery = from n in names
where n.Name.Equals(queryInfo.Name, StringComparison.InvariantCultureIgnoreCase) &&
n.State == queryInfo.State &&
n.Year >= yearStart && n.Year <= yearEnd
orderby n.Year ascending
select n;

parQuery = from n in names.AsParallel().WithDegreeOfParallelism(ProcessorsToUse.Value)
where n.Name.Equals(queryInfo.Name, StringComparison.InvariantCultureIgnoreCase) &&
n.State == queryInfo.State &&
n.Year >= yearStart && n.Year <= yearEnd
orderby n.Year ascending
select n;

The .NET 4 Training Kit has Extensibility demos, and Office Demos and SharePoint Demos and Data Access Demos and on and on. It's great fun and it's a classroom in a box. I encourage you to go download it and use it as a teaching tool at your company or school. You could do brown bags, study groups, presentations (there's lots of PPTs), labs and more.

.NET 4培训工具包具有可扩展性演示以及Office演示,SharePoint演示和数据访问演示等。 这很有趣,而且是一间装在盒子里的教室。 我鼓励您下载它并将其用作公司或学校的教学工具。 您可以做棕色袋子,研究小组,演示文稿(有很多PPT),实验室等等。

Hope you enjoy it as much as I do.

希望您能像我一样喜欢它。

翻译自: https://www.hanselman.com/blog/the-weekly-source-code-56-visual-studio-2010-and-net-framework-4-training-kit-code-contracts-parallel-framework-and-com-interop

知乎周源微信

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值