为什么这不完整?相反,它抛出一个异常,就像没有捕获异常一样.而且,"索引超出数组范围"的例外对我来说没有意义.
int n = 3;
string[] names = new string[] { "sally", "fred", "gina" };
Task[] myTasks = new Task[n];
for (int y = 0; y < n; y++)
{
myTasks[y] = Task.Factory.StartNew(() =>
{
Action<string> action = (name) =>
{
try
{
throw new Exception(name + ", I bet you can't catch me.");
}
catch (Exception e)
{
//I caught you... didn't I?
}
};
action(names[y]);
});
}
Task.WaitAll(myTasks);
Console.WriteLine("All tasks complete.");//This line is never reached;
Run Code Online (Sandbox Code Playgroud) int[] div = new int[] {2,3,5};
IEnumerable<int> seq = new int[] {10,15,20,25,30};
int x;
for (int i=0; i<div.Length; i++){
x = div[i];
seq = seq.Where( s=> s%x ==0);
}
seq = seq.ToList();
Run Code Online (Sandbox Code Playgroud)
和
int[] div = new int[] {2,3,5};
IEnumerable<int> seq = new int[] {10,15,20,25,30};
for (int i=0; i<div.Length; i++){
int y = div[i];
seq = seq.Where( s=> s%y ==0);
}
seq = seq.ToList();
Run Code Online (Sandbox Code Playgroud)
第一个seq的最终值是10,15,20,25,30,第二个是30.我对int x;
和 之间的区别有点困惑int y = div[i];.谁可以给我解释一下这个?
谢谢!
我真的不太了解任务和线程.我在嵌套的三个级别中有一个方法for,我希望在不同的线程/任务中多次运行,但是我传递给方法的变量变得疯狂,让我用一些代码解释一下:
List<int> numbers=new List<int>();
for(int a=0;a<=70;a++)
{
for(int b=0;b<=6;b++)
{
for(int c=0;b<=10;c++)
{
Task.Factory.StartNew(()=>MyMethod(numbers,a,b,c));
}
}
}
private static bool MyMethod(List<int> nums,int a,int b,int c)
{
//Really a lot of stuff here
}
Run Code Online (Sandbox Code Playgroud)
这是嵌套,myMethod确实做了很多事情,比如计算一些数字的阶乘,写入不同的文档和匹配响应与组合列表并调用其他小方法,它也有一些返回值(布尔值),但我此刻不要关心他们.问题是没有任务达到目的,就像每次嵌套调用它自己刷新的方法一样,删除以前的实例.它还会给出一个错误,"尝试除以0",其值超过由FORs分隔的值,例如a=71, b=7, c=11所有变量都为空(这就是除以零的原因).我真的不知道如何解决它.
我想结合一些Linq表达式,所以我从下面的文章中提供帮助:
http://www.c-sharpcorner.com/uploadfile/04fe4a/predicate-combinators-in-linq/ 和 http://thanhhh.blogspot.com/2011/10/linq-to-entities-predicatebuilder-and.html
我有一个像这样的通用列表:
List<long> lstPA = new List<long>() { 2, 3 }; // the numbers can be added or removed
Run Code Online (Sandbox Code Playgroud)
如果我在代码下使用合并我的linq表达式,我从db获得正确的结果(记录)(我使用Entity Framework 4.0):
var exp1 = Predicate.FalseExpression<posts>();
exp1 = exp1.Or(x => x.post_author == 2);
exp1 = exp1.Or(x => x.post_author == 3);
Run Code Online (Sandbox Code Playgroud)
但是当我在foreach循环中组合linq表达式时这样:
var exp1 = Predicate.FalseExpression<posts>();
foreach (long id in lstPA)
{
exp1 = exp1.Or(x => x.post_author == id);
}
Run Code Online (Sandbox Code Playgroud)
我无法从db获得正确的结果(记录).
什么是两个代码块之间的差异以及如何解决这个问题(我必须使用foreach循环)?
任何人都可以解释下面的代码中发生了什么?为什么没有印刷品?
var actions = new Action[100];
for(int i=0;i<100;i++)
{
actions[i] = () => DoSomething(i);
}
foreach(var action in actions)
{
action();
}
void DoSomething(int i)
{
if(i % 9 == 0)
Console.WriteLine("{0} is a multiple of 9",i);
}
Run Code Online (Sandbox Code Playgroud) 我正在为自己即将进行的测试做一些工作,发现这个我无法理解的问题.
int[] div = new int[]{2,3,5};
IEnumerable<int>seq = new int[]{10,15,20,25,30};
for(int i = 0; i<div.Length;i++){
int y = div[i];
seq = seq.Where(s => s%y == 0)
}
seq = seq.ToList();
Run Code Online (Sandbox Code Playgroud)
我认为结果序列将是10 15 20 25 30,但实际答案是30.
我尝试自己运行代码,我发现当代码运行for循环时,序列不会重置为原始序列,但它会保留前一个div [i]创建的序列.
例如,当i = 0时,div [0]为2,因此seq选择10,20和30.
当代码进行到i = 1且div [1] = 3时,它用于计算部分的序列仍然是{10,20,30}而不是{10,15,20,25,30}.
有人可以解释原因吗?
当我像这样移动到for循环的外部时,
int[] div = new int[]{2,3,5};
IEnumerable<int>seq = new int[]{10,15,20,25,30};
int y;
for(int i = 0; i<div.Length;i++){
y = div[i];
seq = seq.Where(s => s%y == 0)
}
seq = seq.ToList();
Run Code Online (Sandbox Code Playgroud)
它给出了我期待的答案. …
我有一些按钮,每个按钮代表某个级别,并且想要以编程方式添加侦听器,但不太熟悉 C# 的 lambda 函数(也许是一些闭包的东西?),这就是我现在所做的:
for(int i=0; i<levels.Count; i++){
//omit the making a button snippet
button.GetComponent<Button>().onClick.AddListener(() =>
{
Debug.Log("load Scene");
ApplicationModel.currentLevel = levels[i];
SceneManager.LoadScene("Game");
//Application.LoadLevel("Game");
});
}
Run Code Online (Sandbox Code Playgroud)
但是这条线:
ApplicationModel.currentLevel = levels[i];
Run Code Online (Sandbox Code Playgroud)
levels是一个List<Level>并且ApplicationModel是一个根据这篇文章保存信息的类
,但它不断给出 ArgumentOutOfRangeException:
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[Level].get_Item (Int32 index) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
GameLevelManger+<initScrollPanel>c__AnonStorey0.<>m__0 () (at Assets/GameLevelManger.cs:72)
Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
attempt = 0;
for (int counter = 0; counter < 8; counter++)
{
if (attempt < totalitems)
{
Tasklist<output>.Add(Task.Run(() =>
{
return someasynctask(inputList[attempt]);
}));
}
else
{
break;
}
attempt++;
}
await Task.WhenAll(Tasklist).ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)
例如,我想要 8 个并发任务,每个任务同时处理不同的输入,最后在所有任务完成后检查结果。因为我没有Task.Run() attempt在任务开始之前等待增加的完成,并且当任务开始时, 中可能有一些项目inputList没有被处理或处理了两次或更多次(因为attempt价值的不确定性。
怎么做?
我是新手,并且在C#中有多线程实现。但是结果返回错误。文件的编号为0到1000。但是返回值为1到1000。不是0。请帮助我理解问题。谢谢。
static void Number(int number)
{
List<string> l_number = new List<string>(File.ReadAllLines("number.txt"));
Console.WriteLine(l_number[number]);
}
static void Main(string[] args)
{
List<Thread> l_thread = new List<Thread>();
int soThread = 10;
Thread thread1 = new Thread(delegate ()
{
var numnum = 0;
while (true)
{
for (int i = 0; i < soThread; i++)
{
Thread threadnew = new Thread(delegate ()
{
//Console.WriteLine(numnum);
Number(numnum);
});
threadnew.Start();
l_thread.Add(threadnew);
numnum++;
Thread.Sleep(100);
}
foreach (Thread item in l_thread)
{
item.Join();
}
}
});
Run Code Online (Sandbox Code Playgroud) 只是尝试学习Invoke/BeginInvoke,我遇到了那个问题.
// Update UI
public void UpdateForm(string value) {
txtLog.AppendText(value + "\r\n");
}
// Thread function
private void readSocket() {
string row = "";
while (socket.Connected) {
row = socket.readLine();
if (IsControlValid(this))
BeginInvoke((MethodInvoker)delegate { UpdateForm(String.Copy(row)); });
}
}
Run Code Online (Sandbox Code Playgroud)
使用Invoke方法我的UI更新与正确的文本,而不是如果我使用BegineInvoke我看到错误的文本,即一些文本反复很多时间.我知道那个电话
BeginInvoke((MethodInvoker)delegate { UpdateForm(row); });
Run Code Online (Sandbox Code Playgroud)
也许"行"可以像共享变量一样行为而不是
BeginInvoke((MethodInvoker)delegate { UpdateForm(String.Copy(row)); });
Run Code Online (Sandbox Code Playgroud)
我认为每个BeginInvoke调用都会创建一个"新"委托,因此使用String.Copy必须创建另一个字符串实例,但我看到总是错误的值(重复,ecc).
哪里我错了?
我对线程安全的方法参数的理解是:通过值传递到方法中的参数作为方法调用的参数中给出的数据的副本传递,因此它们对于该方法调用是唯一的,不能由任何其他任务更改。相反,参考参数可能会因在其他任务中运行的代码而易于更改。
话虽如此,我仍然不太清楚为什么下面的代码(不制作循环计数器的本地副本)在每个线程中返回相同的数字。
static void ExampleFunc(int i) =>
Console.WriteLine("task " + i);
Run Code Online (Sandbox Code Playgroud)
for (int i = 0; i < 10; i++)
{
int taskN = i; //local copy instead of i
Task.Run(() => Func(i));
}
Run Code Online (Sandbox Code Playgroud)
实际输出是:任务10十次,
我通过传递taskN而不是i来获得正确的输出(任务1到10)。
由于传递了类型值参数,因此我期望得到相同的结果。
我需要并行运行任务并向它们传输大约 3-5 个参数,但现在我向任务传输了 2 个参数,因此,我总是在控制台中看到值 100。
告诉我我做错了什么?以及如何正确地将参数传递给任务?
class Program
{
static void Main(string[] args)
{
/// Init
string file_name = "unknown.dat";
Action<string, int> action = (msg, count) => Load(msg, count);
/// For
for (int i = 0; i < 100; i++)
{
Task.Factory.StartNew(() => action(file_name, i));
}
/// End
Console.Read();
}
public static void Load(string aFileName, int aCount)
{
Console.WriteLine("Index: {0} ", aCount);
}
}
Run Code Online (Sandbox Code Playgroud)
c# ×12
task ×4
lambda ×2
.net ×1
asynchronous ×1
begininvoke ×1
combiners ×1
concurrency ×1
linq ×1
loops ×1
taskfactory ×1
winforms ×1