本文整理汇总了C#中System.IO.Pipes.NamedPipeClientStream.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# NamedPipeClientStream.Dispose方法的具体用法?C# NamedPipeClientStream.Dispose怎么用?C# NamedPipeClientStream.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Pipes.NamedPipeClientStream
的用法示例。
在下文中一共展示了NamedPipeClientStream.Dispose方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Start
// Use this for initialization
void Start()
{
System.IO.Pipes.NamedPipeClientStream clientStream = new System.IO.Pipes.NamedPipeClientStream ("mypipe");
clientStream.Connect (60);
byte[] buffer = ASCIIEncoding.ASCII.GetBytes ("Connected/n");
Debug.Log ("connected");
clientStream.Write (buffer, 0, buffer.Length);
clientStream.Flush ();
clientStream.Dispose ();
clientStream.Close ();
}
示例2: SendToPipe
void SendToPipe()
{
byte[] buffer = ASCIIEncoding.ASCII.GetBytes ("done");
System.IO.Pipes.NamedPipeClientStream clientStream = new System.IO.Pipes.NamedPipeClientStream ("mypipe");
clientStream.Connect (System.TimeSpan.MaxValue.Seconds);
clientStream.WaitForPipeDrain();
clientStream.Write (buffer, 0, buffer.Length);
clientStream.Flush ();
clientStream.Dispose();
clientStream.Close();
}
示例3: ConnectToMasterPipeAndSendData
public static void ConnectToMasterPipeAndSendData(string data)
{
byte[] stringData = Encoding.UTF8.GetBytes(data);
int stringLength = stringData.Length;
byte[] array = new byte[sizeof(Int32) + stringLength];
using (MemoryStream stream = new MemoryStream(array))
{
byte[] stringLengthData = BitConverter.GetBytes(stringLength);
stream.Write(stringLengthData, 0, stringLengthData.Length);
stream.Write(stringData, 0, stringData.Length);
}
NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "SpeditNamedPipeServer", PipeDirection.Out, PipeOptions.Asynchronous);
pipeClient.Connect(5000);
pipeClient.Write(array, 0, array.Length);
pipeClient.Flush();
pipeClient.Close();
pipeClient.Dispose();
}
示例4: PipeListener
static void PipeListener()
{
try
{
NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "NowPlayingTunes", PipeDirection.InOut, PipeOptions.None);
StreamString ss = new StreamString(pipeClient);
pipeClient.Connect();
String rettext = ss.ReadString();
Console.WriteLine(rettext);
pipeClient.Close();
pipeClient.Dispose();
}
catch (Exception ex)
{
}
if (DebugMode == false)
{
if (TimeoutThread.IsAlive == true)
{
TimeoutThread.Abort();
}
}
}
示例5: SendCommand
private IEnumerable<string> SendCommand(string command, params string[] arguments)
{
if (!IsPowerShellExecutionHostRunning) throw new InvalidOperationException();
hostSemaphore.WaitOne();
try
{
var client = new NamedPipeClientStream(".", currentToken, PipeDirection.InOut);
TextWriter w;
TextReader r;
try
{
client.Connect(CONNECTION_TIMEOUT);
w = new StreamWriter(client, Encoding.UTF8, 4, true);
r = new StreamReader(client, Encoding.UTF8, false, 4, true);
}
catch (TimeoutException)
{
yield break;
}
catch (IOException ioEx)
{
Debug.WriteLine(ioEx);
yield break;
}
w.WriteLine(command);
foreach (var arg in arguments)
{
w.WriteLine(arg);
}
w.Flush();
while (client.IsConnected)
{
var l = r.ReadLine();
if (l != null)
{
yield return l;
}
}
r.Dispose();
client.Dispose();
}
finally
{
hostSemaphore.Release();
}
}
示例6: RunSingleInstance
/// <summary>
/// After registering at least ApplicationStarts, call this method to ensure this instance is the single instance.
/// If this instance is the first (single) instance, the ApplicationStarts event will be triggered.
/// If this instance is not the first (single) instance, the application will be terminated immediately.
/// </summary>
public void RunSingleInstance()
{
// get information from the mutex if we're the first/single instance.
bool owned = false;
mutex = new Mutex(false, "Global\\{" + id.ToString() + "}", out owned);
if (owned) // we "own" the mutex, meaning we're the first instance
{
// inform the application to begin startup
if (ApplicationStarts != null)
ApplicationStarts(this, new EventArgs());
// prepare a named pipe to receive data from subsequent start attempts
ListenNamedPipe();
}
else // In this case, we're a subsequent instance.
{
// Connect to the named pipe, if able, to signal the original instance that subsequent startup has been attempted
// This could be extended to send actual data to the original instance
try
{
var np = new System.IO.Pipes.NamedPipeClientStream(".", id.ToString(), PipeDirection.Out);
np.Connect(0);
np.Dispose();
}
catch { }
// Regardless, shut down immediately
Application.Current.Shutdown();
}
}
示例7: Main
static void Main(string[] args)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format("Global\\{{{0}}}", appGuid);
using (var mutex = new Mutex(false, mutexId))
{
// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
mutex.SetAccessControl(securitySettings);
// edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
// edited by acidzombie24
// mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(500, false);
if (hasHandle == false)
{
if (args.Count() == 1)
{
if (args[0] == "update")
{
//TODO: send message to pipe
NamedPipeClientStream pipe = new NamedPipeClientStream(".", "NXTLibTesterGUI_forceupdatepipe", PipeDirection.Out);
StreamWriter sw = new StreamWriter(pipe);
pipe.Connect();
sw.AutoFlush = true;
sw.WriteLine("Force Update Now!");
pipe.WaitForPipeDrain();
pipe.Dispose();
}
return;
}
MessageBox.Show("Application already running! Close the other instance and try again.",
"Application Running", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (AbandonedMutexException)
{
// Log the fact the mutex was abandoned in another process, it will still get aquired
hasHandle = true;
}
FindNXT.updatewaiting = false;
if (args.Count() == 1)
{
if (args[0] == "update")
{
FindNXT.updatewaiting = true;
}
}
// Perform your work here.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FindNXT());
}
finally
{
// edited by acidzombie24, added if statemnet
if (hasHandle)
mutex.ReleaseMutex();
}
}
}
示例8: Client
//.........这里部分代码省略.........
try
{
int command = brPipe.ReadInt32();
switch (command)
{
case 0:
handler.ResetCard(true);
Log("Reset");
if (cardInserted)
{
var ATR = handler.ATR;
bwPipe.Write((Int32)ATR.Length);
bwPipe.Write(ATR, 0, ATR.Length);
bwPipe.Flush();
}
else
{
bwPipe.Write((Int32)0);
bwPipe.Flush();
}
break;
case 1:
if (cardInserted)
{
var ATR = handler.ATR;
bwPipe.Write((Int32)ATR.Length);
bwPipe.Write(ATR, 0, ATR.Length);
bwPipe.Flush();
}
else
{
bwPipe.Write((Int32)0);
bwPipe.Flush();
}
//if (command == 0)
// logMessage("Reset");
//else
// logMessage("getATR");
break;
case 2:
int apduLen = brPipe.ReadInt32();
byte[] APDU = new byte[apduLen];
brPipe.Read(APDU, 0, apduLen);
byte[] resp = handler.ProcessApdu(APDU);
if (resp != null)
{
bwPipe.Write((Int32)resp.Length);
bwPipe.Write(resp, 0, resp.Length);
}
else
bwPipe.Write((Int32)0);
bwPipe.Flush();
break;
}
}
catch (Exception e)
{
if (!(e is EndOfStreamException) && !(e is ObjectDisposedException))
Log(e.ToString());
if (running)
{
break;
}
else
{
Log("Card Stop");
return;
}
}
}
}
catch (Exception ex)
{
int p = 0;
}
finally
{
if (cardInserted)
{
cardInserted = false;
if (CardInsert != null)
CardInsert(false);
}
DriverConnected = false;
if (pipe.IsConnected)
pipe.Close();
if (eventPipe.IsConnected)
eventPipe.Close();
pipe.Dispose();
eventPipe.Dispose();
}
}
}
catch (Exception ex)
{
Log("Card Exception:" + ex.ToString());
}
}
示例9: Run
//.........这里部分代码省略.........
progressReportInterval = Int32.Parse(command.Parameters["progressReportInterval"]);
dataRecordBatchSize = Int32.Parse(command.Parameters["dataRecordBatchSize"]);
composition.TriggerInvokeTime = triggerInvokeTime;
composition.Parallelized = parallelized;
break;
case "RunSimulation":
lastReport = DateTime.Now;
modelProgress = new Dictionary<string, string>();
composition.CompositionModelProgressChangedHandler += new CompositionModelProgressChangedDelegate(delegate(object sender, string cmGuid, string progress)
{
lock (this)
{
modelProgress[cmGuid] = progress;
if ((DateTime.Now - lastReport).TotalSeconds > progressReportInterval)
{
lastReport = DateTime.Now;
PipeUtil.WriteCommand(bw, new PipeCommand("Progress", modelProgress));
}
}
});
RunSimulation(delegate(object sender, bool succeed)
{
logger.Info("Simulation finished, succeed=" + succeed);
PipeUtil.WriteCommand(bw, new PipeCommand("Progress", modelProgress));
PipeUtil.WriteCommand(bw, new PipeCommand(succeed ? "Completed" : "Failed"));
});
break;
case "PostProcess":
int channel = 0;
foreach (KeyValuePair<string, List<OutputDataProcessor>> p in outputDataProcessors)
{
logger.Info("Post-processing model " + p.Key + "...");
foreach (OutputDataProcessor processor in p.Value)
{
logger.Info("Calling data processor " + processor.GetType().FullName + "...");
List<Stream> openedFs = new List<Stream>();
try
{
// set properties
processor.SetProperties(modelProperties[p.Key]);
// open data readers
foreach (KeyValuePair<string, string> o in outputFiles[p.Key])
{
if (!File.Exists(o.Value)) continue;
Stream fs = new FileStream(o.Value, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
processor.SetDataReader(o.Key, fs);
openedFs.Add(fs);
logger.Info("Opened " + o.Value + " as " + o.Key + ".");
}
// transfer data
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters["ModelId"] = p.Key;
parameters["ClassName"] = processor.GetType().FullName;
parameters["Name"] = processor.GetName();
parameters["Channel"] = channel.ToString();
PipeUtil.WriteCommand(bw, new PipeCommand("DataSet", parameters));
List<string[]> buffer = new List<string[]>();
while (processor.HasNextRecord())
{
buffer.Add(processor.GetNextRecord());
if (buffer.Count >= dataRecordBatchSize)
flushDataRecord(bw, channel.ToString(), buffer);
}
if (buffer.Count > 0)
flushDataRecord(bw, channel.ToString(), buffer);
channel++;
}
finally
{
// clean up
foreach (Stream fs in openedFs)
{
fs.Close();
fs.Dispose();
}
}
}
}
PipeUtil.WriteCommand(bw, new PipeCommand("PostProcessCompleted"));
break;
case "Halt":
isReleased = true;
return;
}
} while (true);
}
}
catch (Exception e)
{
if (!isReleased)
{
logger.Crit("Exception occured during task lifetime: " + e.ToString());
}
}
finally
{
pipeClient.Close();
pipeClient.Dispose();
}
}
示例10: TryOpenInRunningApplication
private bool TryOpenInRunningApplication(string pipeName, string fileName)
{
try
{
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
{
client.Connect(100);
if (client.IsConnected)
{
if (fileName != null)
{
var bytes = Encoding.UTF8.GetBytes(fileName + "\0");
client.Write(bytes, 0, bytes.Length);
client.Dispose();
}
Environment.Exit(0);
//Window.Dispatcher.InvokeAsync(() => Window.Close());
return true;
}
}
}
catch { }
return false;
}
示例11: Main
//.........这里部分代码省略.........
var xml = XElement.Parse(
Encoding.UTF8.GetString(buffer, 0, c)
);
var old = new { Console.ForegroundColor };
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(new { xml });
Console.ForegroundColor = old.ForegroundColor;
// do something with incoming params?
pipeServer.Disconnect();
// server inactive for a moment, update the state and reconnect to next client
InternalMain(
xml.Elements().Select(x => x.Value).ToArray()
);
}
}
var wConnected = false;
new Thread(
delegate ()
{
// allow 100 until we need to take action
Thread.Sleep(100);
if (wConnected)
{
// server already active!
return;
}
AsServerSignal.Set();
// make us a new server
// cmd.exe allows us to survive a process crash.
Console.WriteLine("Process.Start cmd");
Process.Start("cmd.exe", "/K " + typeof(Program).Assembly.Location);
}
)
{
IsBackground = true
}.Start();
Console.WriteLine("connecting to the server...");
var w = new NamedPipeClientStream(".",
Environment.CurrentDirectory.GetHashCode() +
"foo", PipeDirection.Out, PipeOptions.WriteThrough);
Thread.Yield();
w.Connect();
wConnected = true;
Console.WriteLine("connecting to the server... done");
// http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.jmp(v=vs.110).aspx
var bytes = Encoding.UTF8.GetBytes(
new XElement("xml",
from x in args
select new XElement("arg", x)
).ToString()
);
w.Write(bytes, 0, bytes.Length);
w.Flush();
w.Dispose();
//Thread.Sleep(100);
//Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.
//1> at System.Console.ReadKey(Boolean intercept)
//1> at System.Console.ReadKey()
//Debugger.Break();
//Console.ReadKey();
}