如何在C#中与线程共享资源? [英] How can I share resources with threads in C#?

查看:189
本文介绍了如何在C#中与线程共享资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程从特定的plc内存中读取,并且运行良好.现在,我想要的是启动另一个线程来测试系统的行为(模拟第一个线程),以防出现连接问题,当一切正常时,继续第一个线程.但是我认为我会遇到问题,因为这两个线程将需要使用相同的端口.

I have a thread reading from a specific plc's memory and it works perfectly. Now what I want is to start another thread to test the behavior of the system (simulate the first thread) in case of a conectivity issue, and when everything is Ok, continue the first thread. But I think I'll have problems with that because these two threads will need to use the same port.

我的第一个想法是中止第一个线程,启动第二个线程,当一切正常后,中止该线程并重新启动"第一个线程.

My first idea was to abort the first thread, start the second one and when the everything's OK again, abort this thread and 'restart' the first one.

我读过其他论坛,人们说中止或挂起线程是最糟糕的解决方案,并且我读过有关线程同步的信息,但我真的不知道在这种情况下这是否有用,因为我从来没有用过了.

I've read some other forums and people say that aborting or suspending a thread is the worst solution, and I've read about syncronization of threads but I dont really know if this is useful in this case because I've never used it.

我的问题是,解决这种情况的正确方法是什么?

My question is, what is the correct way to solve this kind of situations?

推荐答案

您拥有一个共享资源,需要协调该线程对线程的访问. .NET中有许多机制可用于这种协调.

You have a shared resource that you need to coordinate thread access to. There are a number of mechanisms in .NET available for that coordination.

有一个很棒的资源,它提供了.NET中线程概念的介绍,并以一种易于接近的方式讨论了高级概念

There is a wonderful resource that provides both an introduction to thread concepts in .NET, and discusses advanced concepts in an approachable manner

http://www.albahari.com/threading/

在您的情况下,请查看有关锁定的部分

In your case, have a look at the section on locking

排他锁定用于确保一次只有一个线程可以输入代码的特定部分.两个主要的互斥锁定结构是lock和Mutex.在这两者中,锁构造更快,更方便.但是,互斥锁有一个利基市场,它的锁可以跨越计算机上不同进程中的应用程序.

Exclusive locking is used to ensure that only one thread can enter particular sections of code at a time. The two main exclusive locking constructs are lock and Mutex. Of the two, the lock construct is faster and more convenient. Mutex, though, has a niche in that its lock can span applications in different processes on the computer.

http://www.albahari.com/threading/part2.aspx#_Locking

您可以构造两个线程,以便它们必须获取特定的锁才能与端口一起使用.在启动第二个线程之前,让您的第一个线程释放该锁,然后让第一个线程再次等待获取该锁(第二个线程将保留该锁直到完成).

You can structure your two threads so that they must acquire a specific lock to work with the port. Have your first thread release that lock before you start the second thread, then have the first thread wait to acquire that lock again (which the second thread will hold until done).

这篇关于如何在C#中与线程共享资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆