利用SynchronizationContext跨线程访问
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private struct SynParam
2 {
3 public SynchronizationContext context;
4 public PanelItem item;
5 public string paramName;
6 public object value;
7
8 }
9
10 private void StartRoll()
11 {
12 flag = false;
13 clickFlag = false;
14 if (_Roll == null)
15 {
16 _Roll = new Thread(new ParameterizedThreadStart(Roll));
17 _Roll.Start(new SynParam() { context = SynchronizationContext.Current });
18 }
19
20 }
21
22 void Roll(object state)
23 {
24
25 SynParam pa = (SynParam)state;
26 pa.context.Post(SetArguments,pa);
27
28 }
29
30 private void SetArguments(object param)
31 {
32 try
33 {
34 SynParam pa = (SynParam)param;
35 string argumentName = pa.paramName;
36 object obj = pa.value;
37 PanelItem item = pa.item;
38 if (argumentName == "Location")
39 {
40 Point p = (Point)obj;
41 item.Loc.X = p.X;
42 item.Loc.Y = p.Y;
43 }
44 else if (argumentName == "Opacity")
45 {
46 item.Opacity = (double)obj;
47 }
48 else if (argumentName == "Scale")
49 {
50 item.Scale = (double)obj;
51 }
52 else if (argumentName == "ZIndex")
53 {
54 Canvas.SetZIndex(item, (int)obj);
55 }
56 }
57 catch (Exception e)
58 {
59 }
60 }
2 {
3 public SynchronizationContext context;
4 public PanelItem item;
5 public string paramName;
6 public object value;
7
8 }
9
10 private void StartRoll()
11 {
12 flag = false;
13 clickFlag = false;
14 if (_Roll == null)
15 {
16 _Roll = new Thread(new ParameterizedThreadStart(Roll));
17 _Roll.Start(new SynParam() { context = SynchronizationContext.Current });
18 }
19
20 }
21
22 void Roll(object state)
23 {
24
25 SynParam pa = (SynParam)state;
26 pa.context.Post(SetArguments,pa);
27
28 }
29
30 private void SetArguments(object param)
31 {
32 try
33 {
34 SynParam pa = (SynParam)param;
35 string argumentName = pa.paramName;
36 object obj = pa.value;
37 PanelItem item = pa.item;
38 if (argumentName == "Location")
39 {
40 Point p = (Point)obj;
41 item.Loc.X = p.X;
42 item.Loc.Y = p.Y;
43 }
44 else if (argumentName == "Opacity")
45 {
46 item.Opacity = (double)obj;
47 }
48 else if (argumentName == "Scale")
49 {
50 item.Scale = (double)obj;
51 }
52 else if (argumentName == "ZIndex")
53 {
54 Canvas.SetZIndex(item, (int)obj);
55 }
56 }
57 catch (Exception e)
58 {
59 }
60 }