NamedPipeServer#WaitForConnectionでブロックされたスレッドをシャットダウンする良い方法は何ですか?

StackOverflow https://stackoverflow.com/questions/607872

  •  03-07-2019
  •  | 
  •  

質問

複数のスレッドを生成するアプリケーションを起動します。各スレッドはNamedPipeServer(.net 3.5がNamed Pipe IPCの管理タイプを追加)を作成し、クライアントの接続を待機します(ブロック)。コードは意図したとおりに機能します。

private void StartNamedPipeServer()
  {
    using (NamedPipeServerStream pipeStream =
                    new NamedPipeServerStream(m_sPipeName, PipeDirection.InOut, m_iMaxInstancesToCreate, PipeTransmissionMode.Message, PipeOptions.None))
    {
      m_pipeServers.Add(pipeStream);
      while (!m_bShutdownRequested)
      {
        pipeStream.WaitForConnection();
        Console.WriteLine("Client connection received by {0}", Thread.CurrentThread.Name);
        ....  

今、このプロセスを正常に終了するためのシャットダウンメソッドも必要です。通常のブールフラグisShutdownRequestedトリックを試しました。ただし、WaitForConnection()呼び出しでパイプストリームはブロックされたままであり、スレッドは停止しません。

public void Stop()
{
   m_bShutdownRequested = true;
   for (int i = 0; i < m_iMaxInstancesToCreate; i++)
   {
     Thread t = m_serverThreads[i];
     NamedPipeServerStream pipeStream = m_pipeServers[i];
     if (pipeStream != null)
     {
       if (pipeStream.IsConnected)
          pipeStream.Disconnect();
       pipeStream.Close();
       pipeStream.Dispose();
     }

     Console.Write("Shutting down {0} ...", t.Name);
     t.Join();
     Console.WriteLine(" done!");
   }
} 

Joinは戻りません。

私が試したわけではないが、おそらく動作する可能性のあるオプションは、Thread.Abortを呼び出して例外を食い止めることです。しかし、それは正しいとは思わない..提案

2009年12月22日更新
これを以前に投稿していないことを申し訳ありません。これは、キムハミルトン(BCLチーム)からの返信として受け取ったものです

  

&quot;右&quot;割り込み可能にする方法   WaitForConnectionが呼び出す   BeginWaitForConnection、新しいハンドル   コールバックの接続、およびクローズ   待機を停止するパイプストリーム   接続。パイプが閉じている場合、   EndWaitForConnectionはスローします   ObjectDisposedExceptionは   コールバックスレッドはキャッチ、クリーンアップできます   端が緩んでいない場合、きれいに終了します。

     

これは一般的なものでなければならないことを認識しています   質問なので、私のチームの誰かが   すぐにこれについてブログを書く予定です。

役に立ちましたか?

解決

非同期バージョンへの切り替え: BeginWaitForConnection

完了した場合は、フラグが必要になります。これにより、完了ハンドラーは EndWaitForConnection を呼び出して例外を吸収し、終了します(End ...を呼び出してリソースをクリーンアップできるようにします) up)。

他のヒント

これは安っぽいですが、私が仕事を始めた唯一の方法です。 「偽の」クライアントを作成し、名前付きパイプに接続して、WaitForConnectionを通過します。毎回動作します。

また、Thread.Abort()でさえ、この問題を修正しませんでした。


_pipeserver.Dispose();
_pipeserver = null;

using (NamedPipeClientStream npcs = new NamedPipeClientStream("pipename")) 
{
    npcs.Connect(100);
}

次の拡張方法を使用できます。 'ManualResetEvent cancelEvent'が含まれていることに注意してください。このイベントを別のスレッドから設定して、待機中の接続メソッドを今すぐ中止してパイプを閉じるように通知できます。 m_bShutdownRequestedを設定するときにcancelEvent.Set()を含めると、シャットダウンは比較的正常になります。

    public static void WaitForConnectionEx(this NamedPipeServerStream stream, ManualResetEvent cancelEvent)
    {
        Exception e = null;
        AutoResetEvent connectEvent = new AutoResetEvent(false);
        stream.BeginWaitForConnection(ar =>
        {
            try
            {
                stream.EndWaitForConnection(ar);
            }
            catch (Exception er)
            {
                e = er;
            }
            connectEvent.Set();
        }, null);
        if (WaitHandle.WaitAny(new WaitHandle[] { connectEvent, cancelEvent }) == 1)
            stream.Close();
        if (e != null)
            throw e; // rethrow exception
    }

この問題を解決するためにこの拡張メソッドを作成しました:

public static void WaitForConnectionEx(this NamedPipeServerStream stream)
{
    var evt = new AutoResetEvent(false);
    Exception e = null;
    stream.BeginWaitForConnection(ar => 
    {
        try
        {
            stream.EndWaitForConnection(ar);
        }
        catch (Exception er)
        {
            e = er;
        }
        evt.Set();
    }, null);
    evt.WaitOne();
    if (e != null)
        throw e; // rethrow exception
}

機能する1つの方法は、WaitForConnectionの直後にm_bShutdownRequestedをチェックすることです。

シャットダウンプロセス中にブール値を設定します。その後、ダミーメッセージを既存のすべてのパイプに送信して、接続を開き、boolを確認して、正常にシャットダウンします。

最も簡単で簡単な解決策は、ダミークライアントを作成し、サーバーと接続することです。

NamedPipeServerStream pServer;
bool exit_flg=false;
    public void PipeServerWaiter()
{

    NamedPipeServerStream  pipeServer = new NamedPipeServerStream("DphPipe", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances);
    pServer = pipeServer;
    pipeServer.WaitForConnection();


    if (exit_flg) return;
    thread = new Thread(PipeServerWaiter);
    thread.Start();

}
public void Dispose()
{
    try
    {
        exit_flg = true;
        NamedPipeClientStream clt = new NamedPipeClientStream(".", "DphPipe");
        clt.Connect();
        clt.Close();

        pServer.Close();
        pServer.Dispose();


    }
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Windows;
using System.Windows.Controls;

namespace PIPESERVER
{
    public partial class PWIN : UserControl
   {
    public string msg = "", cmd = "", text = "";
    public NamedPipeServerStream pipe;
    public NamedPipeClientStream dummyclient;
    public string PipeName = "PIPE1";
    public static string status = "";
    private static int numThreads = 2;
    int threadId;
    int i;
    string[] word;
    char[] buffer;
    public StreamString ss;

    public bool ConnectDummyClient()
    {
        new Thread(() =>
        {
            dummyclient = new NamedPipeClientStream(".", "PIPE1");
            try
            {
                dummyclient.Connect(5000); // 5 second timeout
            }
            catch (Exception e)
            {
                Act.m.md.AMsg(e.Message); // Display error msg
                Act.m.console.PipeButton.IsChecked = false;
            }
        }).Start();
        return true;
    }

    public bool RaisePipe()
    {
        TextBlock tb = Act.m.tb;
        try
        {
            pipe = new NamedPipeServerStream("PIPE1", PipeDirection.InOut, numThreads);
            threadId = Thread.CurrentThread.ManagedThreadId;
            pipe.WaitForConnection();
            Act.m.md.Msg("Pipe Raised");
            return true;
        }
        catch (Exception e)
        {
            string err = e.Message;
            tb.Inlines.Add(new Run("Pipe Failed to Init on Server Side"));
            tb.Inlines.Add(new LineBreak());
            return false;
        }
    }

    public void ServerWaitForMessages()
    {
        new Thread(() =>
        {
            cmd = "";
            ss = new StreamString(pipe);
            while (cmd != "CLOSE")
            {
                try
                {
                    buffer = new char[256];
                    text = "";
                    msg = ss.ReadString().ToUpper();
                    word = msg.Split(' ');
                    cmd = word[0].ToUpper();
                    for (i = 1; i < word.Length; i++) text += word[i] + " ";
                    switch (cmd)
                    {
                        case "AUTHENTICATE": ss.WriteString("I am PIPE1 server"); break;
                        case "SOMEPIPEREQUEST":ss.WriteString(doSomePipeRequestReturningString()):break;
                        case "CLOSE": ss.WriteString("CLOSE");// reply to client
                            Thread.Sleep(1000);// wait for client to pick-up shutdown message
                            pipe.Close();
                            Act.m.md.Msg("Server Shutdown ok"); // Server side message
                            break;
                    }
                }
                catch (IOException iox)
                {
                    string error = iox.Message;
                    Act.m.md.Msg(error);
                    break;
                }
            }
        }).Start();
    }

    public void DummyClientCloseServerRequest()
    {
        StreamString ss = new StreamString(dummyclient);
        ss.WriteString("CLOSE");
        ss.ReadString();
    }

//使用方法、ToggleButtonsをStackPanel内に配置し、コードでそれらをバックします。

private void PipeButton_Checked(object sender, RoutedEventArgs e)
    {
        Act.m.pwin.ConnectDummyClient();
        Act.m.pwin.RaisePipe();
    }
private void PipeButton_Unchecked(object sender, RoutedEventArgs e)
    {
        Act.m.pwin.DummyClientCloseServerRequest();
        Act.m.console.WaitButton.IsChecked = false;
        Keyboard.Focus(Act.m.md.tb1);
    }
private void WaitButton_Checked(object sender, RoutedEventArgs e)
    {
        Act.m.pwin.Wait();
    }
private void WaitButton_Unchecked(object sender, RoutedEventArgs e)
    {
    }

//私にとって魅力的でした。敬具、zzzbc     }

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top