博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#多线程问题
阅读量:5302 次
发布时间:2019-06-14

本文共 1643 字,大约阅读时间需要 5 分钟。

Lambda expressions and captured variables

As we saw, a lambda expression is the most powerfulway to pass data to a thread. However, you must becareful about
accidentally modifying captured variablesafter starting the thread, because these variablesare shared. For instance,
consider the following:

1 for (int i = 0; i < 10; i++) 2 new Thread (() => Console.Write (i)).Start();

The output is nondeterministic! Here’s a typical result:

0223557799
The problem is that the ivariable refers to the samememory location throughout the loop’s lifetime. Therefore, each
thread calls Console.Writeon a variable whose value may change as it is running!
This is analogous to the problem we describe in “Captured Variables” in Chapter 8 of C# 4.0 in a Nutshell. The
problem is less about multithreading and more aboutC#'s rules for capturing variables (which are somewhat
undesirable in the case of forand foreachloops).
The solution is to use a temporary variable as follows:

1 for (int i = 0; i < 10; i++) 2 new Thread (() => Console.Write (i)).Start();

 

Variable tempis now local to each loop iteration. Therefore, each thread captures a different memory location and
there’s no problem. We can illustrate the problem in the earlier code more simply with the following example:
string text = "t1";
Thread t1 = new Thread ( () => Console.WriteLine (t ext) );
text = "t2";
Thread t2 = new Thread ( () => Console.WriteLine (t ext) );
t1.Start();
t2.Start();
Because both lambda expressions capture the same textvariable, t2is printed twice:
t2
t2

转载于:https://www.cnblogs.com/ifutan/archive/2013/06/05/Csharp%e5%a4%9a%e7%ba%bf%e7%a8%8b%e9%97%ae%e9%a2%98.html

你可能感兴趣的文章
veridata实验例(3)验证veridata发现insert操作不会导致同步
查看>>
ExecuteScalar
查看>>
元 变化
查看>>
转_socket函数
查看>>
浅谈数论
查看>>
Android圆角矩形创建工具RoundRect类
查看>>
django数据库交互
查看>>
【转载】SQL注入攻防入门详解
查看>>
图说二叉树添加数据原理以及遍历原理
查看>>
NTC(负温度)热敏电阻.阻值的计算方式
查看>>
ps aux 状态介绍
查看>>
二级指针内存模型
查看>>
bzoj千题计划140:bzoj4519: [Cqoi2016]不同的最小割
查看>>
二进制学习 wsample01a.exe
查看>>
Query Designer:Hierarchy层级显示
查看>>
POJ 3261 可重叠的 k 次最长重复子串【后缀数组】
查看>>
squid
查看>>
Activiti简介
查看>>
CF1157D N Problems During K Days
查看>>
BZOJ4419: [Shoi2013]发微博
查看>>