简体   繁体   English

如何阻塞一个线程,直到另一个线程在 C# 中获得服务器响应

[英]How to block a thread until another thread gets a server response in C#

I am working on a library where you can create a server with a name:我正在开发一个库,您可以在其中创建具有名称的服务器:

UtilityServer server = new UtilityServer("TestServer1", 3500);

You can also create a client with a name:您还可以使用名称创建客户端:

UtilityClient client = new UtilityClient("TestClient1");

The server creates a socket on the local computer with the port you choose.服务器使用您选择的端口在本地计算机上创建一个套接字。 When the server is running, the client can connect via:当服务器运行时,客户端可以通过以下方式连接:

client.Connect(ServerIP, 3500);

Everything works fine when I do it event-based with for example:当我执行基于事件的操作时,一切正常,例如:

client.UserNamesArrived += OnUserNamesArrived;
client.RequestUserNames();

private void OnUserNamesArrived(ReadOnlyCollection<string> userNames)
{
    // Do something with userNames
}

But when I try to create a blocking method in my library for example:但是当我尝试在我的库中创建一个阻塞方法时:

public ReadOnlyCollection<string> GetUserNames()
{
    // Request userNames from server
    // Wait until server sent us userNames
    // return userNames
}

// Running on seperate thread, gets messages that server sents to client
ReceiveMessages()
{
    while(_isConnected)
    {
    // Waits until message is received (_strReader.ReadLine())
    // Looks what message contains (Can also be other things then userNames)
    // Gets collection of userNames when message contains it (Working)
    // Triggers event 'UserNamesArrived' with userNames as argument
    }
}

I don't know how.我不知道怎么做

Now here is my question, how do I wait in my GetUserNames-Thread until my ReceiveMessages-Thread gets the collection of userNames and how can I return them?现在,这里是我的问题,我怎么在等待我的GetUserNames-Thread ,直到我的ReceiveMessages-Thread获取的收集userNames和我怎样才能回报他们?

There are similar Methods in the .Net-Framework that block the Thread, for example: .Net-Framework中也有类似的阻塞线程的方法,例如:

sqlCommand.ExecuteNonQuery();

This also blocks it and waits for a response, but how?这也会阻止它并等待响应,但是如何?

Consider one of the implementations of System.Threading.WaitHandle .考虑System.Threading.WaitHandle的实现之一。

I often use AutoResetEvent for cross thread notifications that require blocking.我经常将AutoResetEvent用于需要阻塞的跨线程通知。

AutoResetEvent allows threads to communicate with each other by signaling. AutoResetEvent 允许线程通过信号相互通信。 Typically, you use this class when threads need exclusive access to a resource.通常,当线程需要独占访问资源时使用此类。

https://msdn.microsoft.com/en-us/library/system.threading.autoresetevent%28v=vs.110%29.aspx https://msdn.microsoft.com/en-us/library/system.threading.autoresetevent%28v=vs.110%29.aspx

You will often hear this construct called a semaphore due to the signalling nature.由于信号的性质,您经常会听到这种称为信号量的构造。 WaitHandles are an OS feature so be make sure you dispose of the handle correctly. WaitHandles 是一项操作系统功能,因此请确保正确处置该句柄。

The significant feature of WaitHandle is the WaitOne method. WaitHandle的显着特征是WaitOne方法。

WaitOneBlocks the current thread until the current WaitHandle receives a signal. WaitOne 阻塞当前线程,直到当前 WaitHandle 接收到信号。

You can use the async and await properties of .NET framework.您可以使用 .NET 框架的 async 和 await 属性。 You'll need to set the ReceiveMessages() method as an async task and make the main thread which runs that method ReadOnlyCollection<string> GetUserNames() wait for the ReceiveMessages() to finish... I think it will work.您需要将ReceiveMessages()方法设置为异步任务,并使运行该方法的主线程ReadOnlyCollection<string> GetUserNames()等待ReceiveMessages()完成......我认为它会起作用。

public async ReadOnlyCollection<string> GetUserNames()
{
    // Request userNames from server
    List<UserNames> userNameList = await ReceiveMessages();
    // return userNames
}

// Running on seperate thread, gets messages that server sents to client
async Task<List<UserNames>> ReceiveMessages()
{
    // Looks what message contains
    // Gets collection of userNames when requested (Working)
    // Triggers event 'UserNamesArrived' with userNames as argument
}

Take a look at that example: await and async example看看那个例子: await 和 async 例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM