Lambda表达式在C#多线程

编程入门 行业动态 更新时间:2024-10-28 13:23:39
本文介绍了Lambda表达式在C#多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想明白为什么这个程序不能正常工作

预计产量:以任意顺序$ B $ 0-19号b口得到什么,当我运行:一些数字重复,有时20印刷

请帮忙。我试图在DoSomething的()锁(OBJ),但它并没有帮助。

程序

使用系统; 使用System.Collections.Generic; 使用System.Linq的; 使用System.Text; 使用的System.Threading; 命名空间ConsoleApplication2 {公众委托无效callbackDelegate(INT X); 类节目 {无效processCallback(INT X) { Console.WriteLine(回调:我得到的值是+ x)的; } 静态无效的主要(字串[] args) {程序P =新计划(); p.processinThreads(); Console.ReadKey(); } 公共无效DoSomething的(INT X,callbackDelegate回调) { Thread.sleep代码(1000); //Console.WriteLine(\"I刚睡醒现在的+ X); 回调(X); } 公共无效processinThreads() {的for(int i = 0; I< 20;我++) {线程t = 新主题(新的ThreadStart(()=> DoSomething的(I,processCallback))); t.Start(); } } } }

解决方案

公共无效processinThreads() {的for(int i = 0; I< 20;我++) { INT本地= I; 线程t =新主题(新的ThreadStart(()=> DoSomething的(本地,processCallback))); t.Start(); } }

您的问题涉及到封闭过的lambda。

I am trying to understand why this program doesn't work

Expected output: numbers 0-19 in random order What I get when I run: some numbers repeat, sometimes 20 is printed.

Please help. I tried with lock(obj) in DoSomething() but it didn't help.

Program

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication2 { public delegate void callbackDelegate(int x); class Program { void processCallback(int x) { Console.WriteLine("IN callback: The value I got is " + x); } static void Main(string[] args) { Program p = new Program(); p.processinThreads(); Console.ReadKey(); } public void DoSomething(int x, callbackDelegate callback) { Thread.Sleep(1000); //Console.WriteLine("I just woke up now " + x); callback(x); } public void processinThreads() { for (int i = 0; i < 20; i++) { Thread t = new Thread(new ThreadStart(()=>DoSomething(i, processCallback))); t.Start(); } } } }

解决方案

public void processinThreads() { for (int i = 0; i < 20; i++) { int local = i; Thread t = new Thread(new ThreadStart(()=>DoSomething(local, processCallback))); t.Start(); } }

Your problem is related to closure over lambda.

更多推荐

Lambda表达式在C#多线程

本文发布于:2023-05-27 19:34:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/300602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   多线程   Lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!