取消BackgroundWorker操作的方法是调用BackgroundWorker.CancelAsync()
:
// RUNNING IN UI THREAD
private void cancelButton_Click(object sender, EventArgs e)
{
backgroundWorker.CancelAsync();
}
Run Code Online (Sandbox Code Playgroud)
在BackgroundWorker.DoWork事件处理程序中,我们检查BackgroundWorker.CancellationPending
:
// RUNNING IN WORKER THREAD
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (!backgroundWorker.CancellationPending) {
DoSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
上述想法遍布整个网络,包括在BackgroundWorker的MSDN页面上.
现在,我的问题是:这个线程安全怎么样?
我已经查看了ILSpy中的BackgroundWorker类 - CancelAsync()
只需将cancellationPending设置为true而不使用内存屏障,CancellationPending
只需返回cancellationPending而不使用内存屏障.
根据这个Jon Skeet页面,上面的内容不是线程安全的.但是BackgroundWorker.CancellationPending的文档说:"这个属性是供工作线程使用的,它应该定期检查CancellationPending并在设置为true时中止后台操作."
这里发生了什么?它是否是线程安全的?
我需要能够说出类似的东西myString.IndexOf(c => !Char.IsDigit(c))
,但我在.NET框架中找不到任何这样的方法.我错过了什么?
以下作品,但滚动我自己似乎有点单调乏味:
using System;
class Program
{
static void Main()
{
string text = "555ttt555";
int nonDigitIndex = text.IndexOf(c => !Char.IsDigit(c));
Console.WriteLine(nonDigitIndex);
}
}
static class StringExtensions
{
public static int IndexOf(this string self, Predicate<char> predicate)
{
for (int index = 0; index < self.Length; ++index) {
if (predicate(self[index])) {
return index;
}
}
return -1;
}
}
Run Code Online (Sandbox Code Playgroud) 以下是使用'动态',在方法IsUnixNewline中,好还是坏?
using System;
class Program
{
static void Main()
{
byte[] bytes = { 32, 32, 32, 10 };
string text = "hello\n";
for (int i = 0; i < bytes.Length; ++i) {
if (IsUnixNewline(bytes, i)) {
Console.WriteLine("Found Unix newline in 'bytes'.");
break;
}
}
for (int i = 0; i < text.Length; ++i) {
if (IsUnixNewline(text, i)) {
Console.WriteLine("Found Unix newline in 'text'.");
break;
}
}
}
static bool IsUnixNewline(dynamic array, int index)
{
return array[index] == '\n' && …
Run Code Online (Sandbox Code Playgroud) 在以下代码中,发生装箱(在Generic <Type> .Print中):
using System;
namespace Test
{
static class Program
{
static void Main()
{
Generic<string> generic = new Generic<string>("test");
generic.Print();
}
}
class Generic<Type>
{
Type value;
public Generic(Type value)
{
this.value = value;
}
public void Print()
{
Console.WriteLine(value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
ILSpy输出:
.method public hidebysig
instance void Print () cil managed
{
// Method begins at RVA 0x207d
// Code size 17 (0x11)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld !0 class Test.Generic`1<!Type>::'value'
IL_0006: box !Type
IL_000b: …
Run Code Online (Sandbox Code Playgroud) 在我的WinForms应用程序中,如果我为我的应用程序设置了一个图标并为我的表单设置了一个图标,则该图标在我的可执行文件中出现两次 有可能避免这种情况吗?
(这个问题已经被问过,在这里,但答案似乎并没有解决问题.vanmelle的答案似乎只提取一个图标(例如,16×16),阳光的回答仅抽出32×32,和LC的回答没有解决问题:可执行文件中仍然存在重复的图标.)
如果无法完成此任务,为什么会这样?在WinForms中使用相同的图标作为可执行文件和表单是什么?