Here are the examples of the csharp api System.Threading.EventWaitHandle.Reset() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
706 Examples
19
Source : XAudio2Stream.cs
with MIT License
from BleuBleu
with MIT License
from BleuBleu
public void Start()
{
Debug.replacedert(sourceVoice == null);
sourceVoice = new SourceVoice(xaudio2, waveFormat);
sourceVoice.BufferEnd += SourceVoice_BufferEnd;
sourceVoice.Start();
quitEvent.Reset();
try
{
while (true) bufferSemapreplaced.Release();
}
catch (SemapreplacedFullException)
{
}
playingTask = Task.Factory.StartNew(PlayAsync, TaskCreationOptions.LongRunning);
}
19
Source : GrowlService.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public void Wait(int timeoutMs)
{
try
{
if (!_autoEvent.WaitOne(timeoutMs))
{
throw new GrowlException(ErrorCode.TIMED_OUT, ErrorDescription.TIMED_OUT, null);
}
if (_isError)
{
throw new GrowlException(_code, _description, null);
}
}
finally
{
_autoEvent.Reset();
_isError = false;
_code = 0;
_description = null;
}
}
19
Source : SingleThreadHost.cs
with MIT License
from bryanperris
with MIT License
from bryanperris
private void RunLoop()
{
m_Exception = null;
m_Running = true;
m_StartWaitEvent.Set();
bool paused = true;
var debugger = m_System.Dbg;
// m_SiReadyDelayTimer = new Timer((_) => m_System.DeviceRcp.SerialDevice.SignalSiReady(), null, 7000, 0);
debugger.DebugBreak += () => {
m_System.DeviceCPU.Debugger.Break();
m_System.DeviceRcp.DeviceRsp.Debugger.Break();
Log.Info("BREAK...@" + m_System.DeviceCPU.ReadPC().ToString("X8"));
};
debugger.DebugContinue += () => {
m_System.DeviceCPU.Debugger.Continue();
m_System.DeviceRcp.DeviceRsp.Debugger.Continue();
Log.Info("CONTINUE...@" + m_System.DeviceCPU.ReadPC().ToString("X8"));
};
try
{
if (CoreConfig.Current.WorkbenchMode) {
while (!m_SignalExit)
{
if (m_Exception != null) throw m_Exception;
// Debugger break active, do not do anything
if (debugger.IsBreakActive) {
if (!paused) {
// TODO: Report RSP break
paused = true;
}
Thread.Sleep(100);
continue;
}
if (paused) {
paused = false;
}
// System core step
m_System.Tick();
// RSP step
// while (!m_System.DeviceRcp.DeviceRsp.IsHalted)
m_System.DeviceRcp.DeviceRsp.Step();
if (debugger.StepNext || debugger.StepRspNext) {
debugger.Break();
}
if (!debugger.IsBreakActive && m_System.DeviceCPU.Debugger.IsBreakActive) {
debugger.Break();
}
if (!debugger.IsBreakActive && m_System.DeviceRcp.DeviceRsp.Debugger.IsBreakActive) {
debugger.Break();
}
}
}
else {
while (!m_SignalExit)
{
if (m_Exception != null) throw m_Exception;
// System core step
m_System.Tick();
// RSP step
// while (!m_System.DeviceRcp.DeviceRsp.IsHalted)
m_System.DeviceRcp.DeviceRsp.Step();
}
}
m_ExitWait.Set();
}
catch (Exception e)
{
Log.Error(e);
m_Exception = e;
}
finally
{
m_Running = false;
m_StartWaitEvent.Reset();
m_System.TickFinally();
m_ExitWait.Set();
}
}
19
Source : ScriptGenerationClient.cs
with MIT License
from cake-build
with MIT License
from cake-build
private async Task RunAsync(CancellationToken cancellationToken)
{
_logger.LogDebug("Waiting for server to connect");
using (var client = await _listener.AcceptTcpClientAsync())
{
_logger.LogDebug("Server connected");
_stream = client.GetStream();
_reader = new BinaryReader(_stream);
_writer = new BinaryWriter(_stream);
_initializedEvent.Set();
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(100, cancellationToken);
}
}
_logger.LogDebug("Shutting down");
_initializedEvent.Reset();
_listener.Stop();
}
19
Source : InteractiveBrokersBrokerage.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void Connect()
{
if (IsConnected) return;
// we're going to receive fresh values for all account data, so we clear all
_accountData.Clear();
var attempt = 1;
const int maxAttempts = 5;
var subscribedSymbolsCount = _subscribedSymbols.Skip(0).Count();
if (subscribedSymbolsCount > 0)
{
Log.Trace($"InteractiveBrokersBrokerage.Connect(): Data subscription count {subscribedSymbolsCount}, restoring data subscriptions is required");
}
while (true)
{
try
{
Log.Trace("InteractiveBrokersBrokerage.Connect(): Attempting to connect ({0}/{1}) ...", attempt, maxAttempts);
// if message processing thread is still running, wait until it terminates
Disconnect();
// At initial startup or after a gateway restart, we need to wait for the gateway to be ready for a connect request.
// Attempting to connect to the socket too early will get a SocketException: Connection refused.
if (attempt == 1)
{
Thread.Sleep(2500);
}
_connectEvent.Reset();
// we're going to try and connect several times, if successful break
Log.Trace("InteractiveBrokersBrokerage.Connect(): calling _client.ClientSocket.eConnect()");
_client.ClientSocket.eConnect(_host, _port, ClientId);
if (!_connectEvent.WaitOne(TimeSpan.FromSeconds(15)))
{
Log.Error("InteractiveBrokersBrokerage.Connect(): timeout waiting for connect callback");
}
// create the message processing thread
var reader = new EReader(_client.ClientSocket, _signal);
reader.Start();
_messageProcessingThread = new Thread(() =>
{
Log.Trace("InteractiveBrokersBrokerage.Connect(): IB message processing thread started: #" + Thread.CurrentThread.ManagedThreadId);
while (_client.ClientSocket.IsConnected())
{
try
{
_signal.waitForSignal();
reader.processMsgs();
}
catch (Exception error)
{
// error in message processing thread, log error and disconnect
Log.Error("InteractiveBrokersBrokerage.Connect(): Error in message processing thread #" + Thread.CurrentThread.ManagedThreadId + ": " + error);
}
}
Log.Trace("InteractiveBrokersBrokerage.Connect(): IB message processing thread ended: #" + Thread.CurrentThread.ManagedThreadId);
})
{ IsBackground = true };
_messageProcessingThread.Start();
// pause for a moment to receive next valid ID message from gateway
if (!_waitForNextValidId.WaitOne(15000))
{
Log.Trace("InteractiveBrokersBrokerage.Connect(): Operation took longer than 15 seconds.");
// no response, disconnect and retry
Disconnect();
// max out at 5 attempts to connect ~1 minute
if (attempt++ < maxAttempts)
{
Thread.Sleep(1000);
continue;
}
throw new TimeoutException("InteractiveBrokersBrokerage.Connect(): Operation took longer than 15 seconds.");
}
Log.Trace("InteractiveBrokersBrokerage.Connect(): IB next valid id received.");
if (!_client.Connected) throw new Exception("InteractiveBrokersBrokerage.Connect(): Connection returned but was not in connected state.");
// request account information for logging purposes
_client.ClientSocket.reqAccountSummary(GetNextId(), "All", "AccountType");
_client.ClientSocket.reqManagedAccts();
_client.ClientSocket.reqFamilyCodes();
if (IsFinancialAdvisor)
{
if (!DownloadFinancialAdvisorAccount(_account))
{
Log.Trace("InteractiveBrokersBrokerage.Connect(): DownloadFinancialAdvisorAccount failed.");
Disconnect();
if (_accountHoldingsLastException != null)
{
// if an exception was thrown during account download, do not retry but exit immediately
attempt = maxAttempts;
throw new Exception(_accountHoldingsLastException.Message, _accountHoldingsLastException);
}
if (attempt++ < maxAttempts)
{
Thread.Sleep(1000);
continue;
}
throw new TimeoutException("InteractiveBrokersBrokerage.Connect(): DownloadFinancialAdvisorAccount failed.");
}
}
else
{
if (!DownloadAccount(_account))
{
Log.Trace("InteractiveBrokersBrokerage.Connect(): DownloadAccount failed. Operation took longer than 15 seconds.");
Disconnect();
if (_accountHoldingsLastException != null)
{
// if an exception was thrown during account download, do not retry but exit immediately
attempt = maxAttempts;
throw new Exception(_accountHoldingsLastException.Message, _accountHoldingsLastException);
}
if (attempt++ < maxAttempts)
{
Thread.Sleep(1000);
continue;
}
throw new TimeoutException("InteractiveBrokersBrokerage.Connect(): DownloadAccount failed.");
}
}
// enable logging at Warning level
_client.ClientSocket.setServerLogLevel(3);
break;
}
catch (Exception err)
{
// max out at 5 attempts to connect ~1 minute
if (attempt++ < maxAttempts)
{
Thread.Sleep(15000);
continue;
}
// we couldn't connect after several attempts, log the error and throw an exception
Log.Error(err);
throw;
}
}
// if we reached here we should be connected, check just in case
if (IsConnected)
{
Log.Trace("InteractiveBrokersBrokerage.Connect(): Restoring data subscriptions...");
RestoreDataSubscriptions();
}
else
{
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, "ConnectionState", "Unexpected, not connected state. Unable to connect to Interactive Brokers. Terminating algorithm."));
}
}
19
Source : InteractiveBrokersBrokerage.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private void HandlePortfolioUpdates(object sender, IB.UpdatePortfolioEventArgs e)
{
try
{
Log.Trace($"InteractiveBrokersBrokerage.HandlePortfolioUpdates(): {e}");
// notify the transaction handler about all option position updates
if (e.Contract.SecType is IB.SecurityType.Option or IB.SecurityType.FutureOption)
{
var symbol = MapSymbol(e.Contract);
OnOptionNotification(new OptionNotificationEventArgs(symbol, e.Position));
}
_accountHoldingsResetEvent.Reset();
if (_loadExistingHoldings)
{
var holding = CreateHolding(e);
_accountData.AccountHoldings[holding.Symbol.Value] = holding;
}
}
catch (Exception exception)
{
Log.Error($"InteractiveBrokersBrokerage.HandlePortfolioUpdates(): {exception}");
if (e.Position != 0)
{
// Force a runtime error only with a nonzero position for an unsupported security type,
// because after the user has manually closed the position and restarted the algorithm,
// he'll have a zero position but a nonzero realized PNL, so this event handler will be called again.
_accountHoldingsLastException = exception;
_accountHoldingsResetEvent.Set();
}
}
}
19
Source : BitfinexBrokerage.DataQueueHandler.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private bool SubscribeChannel(IWebSocket webSocket, string channelName, Symbol symbol)
{
_onSubscribeEvent.Reset();
webSocket.Send(JsonConvert.SerializeObject(new
{
@event = "subscribe",
channel = channelName,
pair = _symbolMapper.GetBrokerageSymbol(symbol)
}));
if (!_onSubscribeEvent.WaitOne(TimeSpan.FromSeconds(30)))
{
Log.Error($"BitfinexBrokerage.Unsubscribe(): Could not subscribe to {symbol.Value}/{channelName}.");
return false;
}
return true;
}
19
Source : BitfinexBrokerage.DataQueueHandler.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private bool UnsubscribeChannel(IWebSocket webSocket, BitfinexWebSocketChannels channels, Channel channel)
{
if (channels.Contains(channel))
{
var channelId = channels.GetChannelId(channel);
_onUnsubscribeEvent.Reset();
webSocket.Send(JsonConvert.SerializeObject(new
{
@event = "unsubscribe",
chanId = channelId.ToStringInvariant()
}));
if (!_onUnsubscribeEvent.WaitOne(TimeSpan.FromSeconds(30)))
{
Log.Error($"BitfinexBrokerage.Unsubscribe(): Could not unsubscribe from {channel.Symbol.Value}/{channel.Name}.");
return false;
}
}
return true;
}
19
Source : InteractiveBrokersBrokerage.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private bool DownloadAccount(string account)
{
Log.Trace($"InteractiveBrokersBrokerage.DownloadAccount(): Downloading account data for {account}");
_accountHoldingsLastException = null;
_accountHoldingsResetEvent.Reset();
// define our event handler, this acts as stop to make sure when we leave Connect we have downloaded the full account
EventHandler<IB.AccountDownloadEndEventArgs> clientOnAccountDownloadEnd = (sender, args) =>
{
Log.Trace("InteractiveBrokersBrokerage.DownloadAccount(): Finished account download for " + args.Account);
_accountHoldingsResetEvent.Set();
};
_client.AccountDownloadEnd += clientOnAccountDownloadEnd;
// we'll wait to get our first account update, we need to be absolutely sure we
// have downloaded the entire account before leaving this function
var firstAccountUpdateReceived = new ManualResetEvent(false);
EventHandler<IB.UpdateAccountValueEventArgs> clientOnUpdateAccountValue = (sender, args) =>
{
firstAccountUpdateReceived.Set();
};
_client.UpdateAccountValue += clientOnUpdateAccountValue;
// first we won't subscribe, wait for this to finish, below we'll subscribe for continuous updates
_client.ClientSocket.reqAccountUpdates(true, account);
// wait to see the first account value update
firstAccountUpdateReceived.WaitOne(2500);
// take pause to ensure the account is downloaded before continuing, this was added because running in
// linux there appears to be different behavior where the account download end fires immediately.
Thread.Sleep(2500);
if (!_accountHoldingsResetEvent.WaitOne(15000))
{
// remove our event handlers
_client.AccountDownloadEnd -= clientOnAccountDownloadEnd;
_client.UpdateAccountValue -= clientOnUpdateAccountValue;
Log.Trace("InteractiveBrokersBrokerage.DownloadAccount(): Operation took longer than 15 seconds.");
return false;
}
// remove our event handlers
_client.AccountDownloadEnd -= clientOnAccountDownloadEnd;
_client.UpdateAccountValue -= clientOnUpdateAccountValue;
return _accountHoldingsLastException == null;
}
19
Source : SpeechCutterClient.cs
with MIT License
from carlfm01
with MIT License
from carlfm01
public bool CutSentence(string sentence, string inputWav, string outputDirectory, double confidence, Formats targetFormat)
{
_singleSentenceRecognition = true;
_confidence = confidence;
VerifyOutputDirectory(outputDirectory);
_speechRecognitionEngine.SetInputToWaveFile(inputWav);
_speechRecognitionEngine.LoadGrammar(CreateGrammar(sentence));
_speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
_eventLock.WaitOne();
_eventLock.Reset();
_speechRecognitionEngine.UnloadAllGrammars();
CutRecognizedSentences(inputWav, outputDirectory, targetFormat);
return _recognizedSentences.Count != 0;
}
19
Source : SpeechCutterClient.cs
with MIT License
from carlfm01
with MIT License
from carlfm01
public bool CutSentences(string[] sentences, string inputWav, string outputDirectory, double confidence, Formats targetFormat)
{
_singleSentenceRecognition = false;
_confidence = confidence;
VerifyOutputDirectory(outputDirectory);
_speechRecognitionEngine.SetInputToWaveFile(inputWav);
foreach (string sentence in sentences)
{
_speechRecognitionEngine.LoadGrammar(CreateGrammar(sentence));
}
_speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
_eventLock.WaitOne();
_eventLock.Reset();
_speechRecognitionEngine.UnloadAllGrammars();
CutRecognizedSentences(inputWav, outputDirectory, targetFormat);
return _recognizedSentences.Count != 0;
}
19
Source : ValueChangedNotifyProcesser.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void ThreadProcess()
{
int i = 0;
while (!mIsClosed)
{
resetEvent.WaitOne();
if (mIsClosed) break;
resetEvent.Reset();
if (NotifyType == RealDataNotifyType.Tag || NotifyType == RealDataNotifyType.All)
{
if (ValueChanged != null && mChangedIds.Length > 0)
{
var vids = mChangedIds;
lock (mLockObject)
{
if (mChangedIds == mChangedId1)
{
mChangedIds = mChangedId2;
}
else
{
mChangedIds = mChangedId1;
}
}
ValueChanged?.Invoke(vids.Buffer, vids.Length);
vids.Length = 0;
}
}
if (NotifyType == RealDataNotifyType.All || NotifyType == RealDataNotifyType.Block)
{
if ((BlockChanged != null) && i % 10 == 0)
{
i = 0;
lock (mBlockChangeds)
{
foreach (var vv in mBlockChangeds)
{
if (vv.Value.IsDirty)
{
vv.Value.IsDirty = false;
BlockChanged?.Invoke(vv.Value);
}
}
}
}
}
i++;
Thread.Sleep(10);
}
}
19
Source : ProducterValueChangedNotifyProcesser.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void ThreadProcess()
{
while(true)
{
resetEvent.WaitOne();
if (mIsClosed) break;
resetEvent.Reset();
if (mChangedIds.Count > 0)
{
lock (mLockObject)
{
ValueChanged?.Invoke(mChangedIds);
mChangedIds.Clear();
}
}
}
}
19
Source : Driver.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void CosThreadPro()
{
ThreadHelper.replacedignToCPU(CPUreplacedignHelper.Helper.CPUArray2);
List<Tagbase> vv = mTagIdCach.ContainsKey("Sim:cos") ? mTagIdCach["Sim:cos"] : null;
List<int> vvr = mManualRecordTagCach.ContainsKey("Sim:cos") ? mManualRecordTagCach["Sim:cos"] : null;
//mCosStopwatch = new Stopwatch();
while (!mIsClosed)
{
mCosEvent.WaitOne();
mCosEvent.Reset();
if(mCosNeedReload)
{
vv = mTagIdCach.ContainsKey("Sim:cos") ? mTagIdCach["Sim:cos"] : null;
vvr = mManualRecordTagCach.ContainsKey("Sim:cos") ? mManualRecordTagCach["Sim:cos"] : null;
mCosNeedReload = false;
}
//mCosStopwatch.Restart();
//long ll = 0;
double fval = Math.Cos(mNumber / 180.0 * Math.PI);
if (vv!=null)
{
mTagService.SetTagValue(vv,ref fval, 0);
//ll = mCosStopwatch.ElapsedMilliseconds;
mTagService.SubmiteNotifyChanged();
}
if (vvr != null && vvr.Count>0)
{
TagValue tv = new TagValue() { Quality = 0, Time = DateTime.UtcNow, Value = fval };
foreach (var vvv in vvr)
{
mTagHisValueService.SetTagHisValue(vvv, tv);
}
}
//mCosStopwatch.Stop();
//LoggerService.Service.Info("SimDriver", "设置变量耗时:" + ll + " 其他耗时:" + (mCosStopwatch.ElapsedMilliseconds - ll) + " count:" + vv.Count);
var ts = (DateTime.Now - mLastProcessTime).TotalMilliseconds;
lock (mLockObj)
{
if (ts > mMaxProcessTimeSpan)
{
mMaxProcessTimeSpan = ts;
//mSelfProcessTimeSpan = mCosStopwatch.ElapsedMilliseconds;
}
}
Interlocked.Increment(ref mFinishCount);
}
}
19
Source : Driver.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void SinThreadPro()
{
ThreadHelper.replacedignToCPU(CPUreplacedignHelper.Helper.CPUArray2);
List<Tagbase> vv = mTagIdCach.ContainsKey("Sim:sin") ? mTagIdCach["Sim:sin"] : null;
List<int> vvr = mManualRecordTagCach.ContainsKey("Sim:sin") ? mManualRecordTagCach["Sim:sin"] : null;
//mSinStopwatch = new Stopwatch();
while (!mIsClosed)
{
mSinEvent.WaitOne();
mSinEvent.Reset();
if(mSinNeedReload)
{
vv = mTagIdCach.ContainsKey("Sim:sin") ? mTagIdCach["Sim:sin"] : null;
vvr = mManualRecordTagCach.ContainsKey("Sim:sin") ? mManualRecordTagCach["Sim:sin"] : null;
mSinNeedReload = false;
}
//mSinStopwatch.Restart();
double fval = Math.Sin(mNumber / 180.0 * Math.PI);
if (vv != null)
{
mTagService.SetTagValue(vv,ref fval, 0);
mTagService.SubmiteNotifyChanged();
}
if (vvr != null && vvr.Count > 0)
{
TagValue tv = new TagValue() { Quality = 0, Time = DateTime.UtcNow, Value = fval };
foreach (var vvv in vvr)
{
mTagHisValueService.SetTagHisValue(vvv, tv);
}
}
//mSinStopwatch.Stop();
var ts = (DateTime.Now - mLastProcessTime).TotalMilliseconds;
lock (mLockObj)
{
if (ts > mMaxProcessTimeSpan)
{
mMaxProcessTimeSpan = ts;
//mSelfProcessTimeSpan = mSinStopwatch.ElapsedMilliseconds;
}
}
Interlocked.Increment(ref mFinishCount);
}
}
19
Source : Driver.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void StepThreadPro()
{
ThreadHelper.replacedignToCPU(CPUreplacedignHelper.Helper.CPUArray2);
List<Tagbase> vv = mTagIdCach.ContainsKey("Sim:step") ? mTagIdCach["Sim:step"] : null;
List<int> vvr = mManualRecordTagCach.ContainsKey("Sim:step") ? mManualRecordTagCach["Sim:step"] : null;
//mStepStopwatch = new Stopwatch();
while (!mIsClosed)
{
mStepEvent.WaitOne();
mStepEvent.Reset();
if(mStepNeedReload)
{
vv = mTagIdCach.ContainsKey("Sim:step") ? mTagIdCach["Sim:step"] : null;
vvr = mManualRecordTagCach.ContainsKey("Sim:step") ? mManualRecordTagCach["Sim:step"] : null;
mStepNeedReload = false;
}
//mStepStopwatch.Restart();
if (vv != null)
{
mTagService.SetTagValue(vv,ref mNumber, 0);
mTagService.SubmiteNotifyChanged();
}
if (vvr != null && vvr.Count > 0)
{
TagValue tv = new TagValue() { Quality = 0, Time = DateTime.UtcNow, Value = mNumber };
foreach (var vvv in vvr)
{
mTagHisValueService.SetTagHisValue(vvv, tv);
}
}
//mStepStopwatch.Stop();
var ts = (DateTime.Now - mLastProcessTime).TotalMilliseconds;
lock (mLockObj)
{
if (ts > mMaxProcessTimeSpan)
{
mMaxProcessTimeSpan = ts;
//mSelfProcessTimeSpan = mStepStopwatch.ElapsedMilliseconds;
}
}
Interlocked.Increment(ref mFinishCount);
}
}
19
Source : Driver.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void StepPointThreadPro()
{
ThreadHelper.replacedignToCPU(CPUreplacedignHelper.Helper.CPUArray2);
List<Tagbase> vv = mTagIdCach.ContainsKey("Sim:steppoint") ? mTagIdCach["Sim:steppoint"] : null;
List<int> vvr = mManualRecordTagCach.ContainsKey("Sim:steppoint") ? mManualRecordTagCach["Sim:steppoint"] : null;
while (!mIsClosed)
{
mSteppointEvent.WaitOne();
mSteppointEvent.Reset();
if(mStepPointNeedReload)
{
vv = mTagIdCach.ContainsKey("Sim:steppoint") ? mTagIdCach["Sim:steppoint"] : null;
vvr = mManualRecordTagCach.ContainsKey("Sim:steppoint") ? mManualRecordTagCach["Sim:steppoint"] : null;
mStepPointNeedReload = false;
}
var vpp = new IntPoint3Data(mNumber, mNumber, mNumber);
if (vv != null)
{
mTagService.SetTagValue(vv ,ref vpp, 0);
mTagService.SubmiteNotifyChanged();
}
if (vvr != null && vvr.Count > 0)
{
TagValue tv = new TagValue() { Quality = 0, Time = DateTime.UtcNow, Value = new IntPoint3Data(mNumber, mNumber, mNumber) };
foreach (var vvv in vvr)
{
mTagHisValueService.SetTagHisValue(vvv, tv);
}
}
var ts = (DateTime.Now - mLastProcessTime).TotalMilliseconds;
lock (mLockObj)
{
if (ts > mMaxProcessTimeSpan)
{
mMaxProcessTimeSpan = ts;
}
}
Interlocked.Increment(ref mFinishCount);
}
}
19
Source : Driver.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void SquareThreadPro()
{
ThreadHelper.replacedignToCPU(CPUreplacedignHelper.Helper.CPUArray2);
List<Tagbase> vv = mTagIdCach.ContainsKey("Sim:square") ? mTagIdCach["Sim:square"] : null;
List<int> vvr = mManualRecordTagCach.ContainsKey("Sim:square") ? mManualRecordTagCach["Sim:square"] : null;
while (!mIsClosed)
{
mSquareEvent.WaitOne();
mSquareEvent.Reset();
if(mSquareNeedReload)
{
vv = mTagIdCach.ContainsKey("Sim:square") ? mTagIdCach["Sim:square"] : null;
vvr = mManualRecordTagCach.ContainsKey("Sim:square") ? mManualRecordTagCach["Sim:square"] : null;
mSquareNeedReload = false;
}
if (vv != null)
{
mTagService.SetTagValue(vv,ref mBoolNumber, 0);
mTagService.SubmiteNotifyChanged();
}
if (vvr != null && vvr.Count > 0)
{
TagValue tv = new TagValue() { Quality = 0, Time = DateTime.UtcNow, Value = mBoolNumber };
foreach (var vvv in vvr)
{
mTagHisValueService.SetTagHisValue(vvv, tv);
}
}
var ts = (DateTime.Now - mLastProcessTime).TotalMilliseconds;
lock (mLockObj)
{
if (ts > mMaxProcessTimeSpan)
{
mMaxProcessTimeSpan = ts;
}
}
Interlocked.Increment(ref mFinishCount);
}
}
19
Source : ServerProcessBase.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void DataProcess()
{
string sname="";
Queue<ByteBuffer> datas = null;
while (!mIsClosed)
{
resetEvent.WaitOne();
if (mIsClosed) return;
resetEvent.Reset();
for (int i = 0; i < mClients.Count; i++)
{
sname = "";
datas = null;
lock (mClients)
{
if (i < mClients.Count)
{
sname = mClients[i];
}
}
if (!string.IsNullOrEmpty(sname))
{
lock (mDatasCach)
{
if (mDatasCach.ContainsKey(sname))
{
datas = mDatasCach[sname];
}
}
if (datas != null)
{
//Stopwatch sw = new Stopwatch();
//sw.Start();
//Debug.Print("开始实时数据请求:" + FunId +" " + datas.Count);
while (datas.Count > 0)
{
ProcessSingleData(sname, datas.Dequeue());
}
//sw.Stop();
//Debug.Print("结束实时数据请求:" + sw.ElapsedMilliseconds);
}
}
}
}
}
19
Source : ServerProcessBase.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void DataProcess()
{
while (!mIsClosed)
{
resetEvent.WaitOne();
if (mIsClosed) return;
resetEvent.Reset();
foreach (var vv in mDatasCach)
{
while(vv.Value.Count>0)
{
var dd = vv.Value.Dequeue();
ProcessSingleData(vv.Key, dd);
}
}
}
}
19
Source : LogManager3.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void SaveProcess()
{
ThreadHelper.replacedignToCPU(CPUreplacedignHelper.Helper.CPUArray2);
while (!mIsExit)
{
resetEvent.WaitOne();
resetEvent.Reset();
if (mIsExit) break;
Stopwatch sw = new Stopwatch();
sw.Start();
if(mNeedSaveMemory1!=null)
{
mNeedSaveMemory1.MakeMemoryBusy();
RecordToFile();
mNeedSaveMemory1.MakeMemoryNoBusy();
ClearMemoryHisData(mNeedSaveMemory1);
}
CheckRemoveOldFiles();
sw.Stop();
LoggerService.Service.Info("LogManager", "记录"+ mNeedSaveMemory1.Name +"到日志文件 耗时" + sw.ElapsedMilliseconds + " ");
}
closedEvent.Set();
LoggerService.Service.Info("LogManager", "退出!");
}
19
Source : TimerMemoryCacheProcesser3.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void ThreadProcess()
{
ThreadHelper.replacedignToCPU(CPUreplacedignHelper.Helper.CPUArray1);
closedEvent.Reset();
var vkeys = mCount.Keys.ToArray();
var vdd = DateTime.UtcNow;
foreach(var vv in vkeys)
{
mCount[vv] = vdd.AddMilliseconds(vv);
}
mLastProcessTime = DateTime.Now;
while (!mIsClosed)
{
resetEvent.WaitOne();
resetEvent.Reset();
if (mIsClosed)
break;
//if(NeedReInit)
//{
// NeedReInit = false;
// vkeys = mCount.Keys.ToArray();
// vdd = DateTime.UtcNow;
// foreach (var vv in vkeys)
// {
// mCount[vv] = vdd.AddMilliseconds(vv);
// }
//}
var dnow = DateTime.Now;
if ((mLastProcessTime - dnow).TotalMilliseconds > 900)
{
LoggerService.Service.Warn("TimerMemoryCacheProcesser", "定时记录超时 "+ (mLastProcessTime - dnow).TotalMilliseconds);
}
mLastProcessTime = dnow;
try
{
mIsBusy = true;
var vdata = mLastUpdateTime;
foreach (var vv in vkeys)
{
if (vdata >= mCount[vv])
{
do
{
mCount[vv] = mCount[vv].AddMilliseconds(vv);
}
while (mCount[vv] <= vdata);
ProcessTags(mTimerTags[vv]);
}
}
mIsBusy = false;
}
catch
{
}
resetEvent.Reset();
}
closedEvent.Set();
LoggerService.Service.Info("TimerMemoryCacheProcesser", Id + " 退出");
}
19
Source : ValueChangedMemoryCacheProcesser3.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void ThreadProcess()
{
ThreadHelper.replacedignToCPU(CPUreplacedignHelper.Helper.CPUArray1);
closedEvent.Reset();
while (!mIsClosed)
{
resetEvent.WaitOne();
resetEvent.Reset();
if (mIsClosed) break;
try
{
int tim = (int)((mLastUpdateTime - HisRunTag.StartTime).TotalMilliseconds / HisEnginer3.MemoryTimeTick);
if (mChangedTags.Count > 0)
{
foreach (var vv in mChangedTags)
{
if (vv.Value)
{
lock (mLockObj)
{
mTags[vv.Key].UpdateChangedValue3(tim);
mChangedTags[vv.Key] = false;
}
}
}
}
}
catch(Exception ex)
{
LoggerService.Service.Erro("ValueChangedMemoryCacheProcesser", ex.Message);
}
resetEvent.Reset();
}
closedEvent.Set();
LoggerService.Service.Info("ValueChangedMemoryCacheProcesser", Name + " 退出");
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public string GetRealdatabase(int timeout = 50000)
{
string filename = string.Empty;
var mb = GetBuffer(ApiFunConst.TagInfoRequest, 1 + 9);
mb.Write(ApiFunConst.SyncRealTagConfig);
mb.Write(LoginId);
this.SyncDataEvent.Reset();
SendData(mb);
if (SyncDataEvent.WaitOne(timeout))
{
try
{
if ((this.mRealSyncData.WriteIndex - mRealSyncData.ReadIndex) > 0)
{
try
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(this.mRealSyncData.ReadBytes((int)(this.mRealSyncData.WriteIndex - mRealSyncData.ReadIndex)));
ms.Position = 0;
System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
filename = System.IO.Path.GetTempFileName();
var sfile = System.IO.File.Open(filename, System.IO.FileMode.OpenOrCreate);
gzip.CopyTo(sfile);
sfile.Close();
ms.Dispose();
gzip.Dispose();
return filename;
}
catch
{
}
}
}
finally
{
mRealSyncData?.UnlockAndReturn();
mRealSyncData = null;
}
}
return filename;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public string GetSecuritySetting(int timeout = 50000)
{
string filename = string.Empty;
var mb = GetBuffer(ApiFunConst.TagInfoRequest, 1 + 9);
mb.Write(ApiFunConst.SyncSecuritySetting);
mb.Write(LoginId);
this.SyncDataEvent.Reset();
SendData(mb);
if (SyncDataEvent.WaitOne(timeout))
{
try
{
if (this.mRealSyncData.WriteIndex - mRealSyncData.ReadIndex > 0)
{
try
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(this.mRealSyncData.ReadBytes((int)(this.mRealSyncData.WriteIndex - mRealSyncData.ReadIndex)));
ms.Position = 0;
System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
filename = System.IO.Path.GetTempFileName();
var sfile = System.IO.File.Open(filename, System.IO.FileMode.OpenOrCreate);
gzip.CopyTo(sfile);
sfile.Close();
ms.Dispose();
gzip.Dispose();
return filename;
}
catch
{
}
}
}
finally
{
mRealSyncData?.UnlockAndReturn();
mRealSyncData = null;
}
}
return filename;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public Dictionary<string, int> GetTagIds(List<string> tagNames, int timeout = 5000)
{
Dictionary<string, int> re = new Dictionary<string, int>();
var mb = GetBuffer(ApiFunConst.TagInfoRequest, tagNames.Count * 24 + 1 + 9);
mb.Write(ApiFunConst.GetTagIdByNameFun);
mb.Write(LoginId);
mb.Write(tagNames.Count);
foreach (var vv in tagNames)
{
mb.Write(vv);
}
infoRequreEvent.Reset();
SendData(mb);
if (infoRequreEvent.WaitOne(timeout))
{
for (int i = 0; i < tagNames.Count; i++)
{
if (mInfoRequreData.WriteIndex - mInfoRequreData.ReadIndex > 0)
re.Add(tagNames[i], mInfoRequreData.ReadInt());
}
mInfoRequreData?.UnlockAndReturn();
mInfoRequreData = null;
}
return re;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public string GetRunnerDatabase(int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.TagInfoRequest, 8 + 1);
mb.Write(ApiFunConst.GetRunnerDatabase);
mb.Write(LoginId);
infoRequreEvent.Reset();
SendData(mb);
if (infoRequreEvent.WaitOne(timeout))
{
try
{
return mInfoRequreData.ReadString();
}
finally
{
mInfoRequreData.UnlockAndReturn();
mInfoRequreData = null;
}
}
return string.Empty;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public bool RegistorTagBlockValueCallBack(int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8);
mb.Write(ApiFunConst.BlockValueChangeNotify);
mb.Write(this.LoginId);
this.realRequreEvent.Reset();
SendData(mb);
if (realRequreEvent.WaitOne(timeout))
{
try
{
return mRealRequreData.ReadByte() > 0;
}
finally
{
mRealRequreData?.UnlockAndReturn();
mRealRequreData = null;
}
}
return true;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ByteBuffer GetRealData(List<int> ids, int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8 + ids.Count * 4);
mb.Write(ApiFunConst.RequestRealData);
mb.Write(this.LoginId);
mb.Write(ids.Count);
for (int i = 0; i < ids.Count; i++)
{
mb.Write(ids[i]);
}
realRequreEvent.Reset();
SendData(mb);
try
{
if (realRequreEvent.WaitOne(timeout))
{
return mRealRequreData;
}
}
finally
{
mRealRequreData = null;
}
return null;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ByteBuffer GetRealDataByMemoryCopy(List<int> ids, int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8 + ids.Count * 4);
mb.Write(ApiFunConst.RequestRealDataByMemoryCopy);
mb.Write(this.LoginId);
mb.Write(ids.Count);
for (int i = 0; i < ids.Count; i++)
{
mb.Write(ids[i]);
}
realRequreEvent.Reset();
SendData(mb);
try
{
if (realRequreEvent.WaitOne(timeout))
{
return mRealRequreData;
}
}
finally
{
mRealRequreData = null;
}
return null;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ByteBuffer GetRealData(int ids, int ide, int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8 + 8);
mb.Write(ApiFunConst.RequestRealData2);
mb.Write(this.LoginId);
mb.Write(ids);
mb.Write(ide);
realRequreEvent.Reset();
SendData(mb);
try
{
if (realRequreEvent.WaitOne(timeout))
{
return mRealRequreData;
}
}
finally
{
mRealRequreData = null;
}
return null;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ByteBuffer SyncRealMemory(int startaddress, int endaddress, int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8 + 4);
mb.Write(ApiFunConst.RealMemorySync);
mb.Write(this.LoginId);
mb.Write((endaddress - startaddress));
mb.Write(startaddress);
realRequreEvent.Reset();
SendData(mb);
if (realRequreEvent.WaitOne(timeout))
{
if (mRealRequreData.WriteIndex - mRealRequreData.ReadIndex == (endaddress - startaddress))
try
{
return mRealRequreData;
}
finally
{
mRealRequreData = null;
}
else
return null;
}
else
{
return null;
}
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ByteBuffer GetRealDataByMemoryCopy(int ids, int ide, int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8 + (ide - ids) * 4);
mb.Write(ApiFunConst.RequestRealData2ByMemoryCopy);
mb.Write(this.LoginId);
mb.Write(ids);
mb.Write(ide);
realRequreEvent.Reset();
SendData(mb);
if (realRequreEvent.WaitOne(timeout))
{
try
{
return mRealRequreData;
}
finally
{
mRealRequreData = null;
}
}
//mRealRequreData?.ReleaseBuffer();
return null;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public bool SetTagValue(int id, byte valueType, object value, int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8 + 30);
mb.Write(ApiFunConst.SetDataValue);
mb.Write(this.LoginId);
mb.Write(1);
mb.Write(id);
mb.WriteByte(valueType);
switch (valueType)
{
case (byte)TagType.Bool:
mb.Write((byte)value);
break;
case (byte)TagType.Byte:
mb.Write((byte)value);
break;
case (byte)TagType.Short:
mb.Write((short)value);
break;
case (byte)TagType.UShort:
mb.Write((ushort)value);
break;
case (byte)TagType.Int:
mb.Write((int)value);
break;
case (byte)TagType.UInt:
mb.Write((int)value);
break;
case (byte)TagType.Long:
case (byte)TagType.ULong:
mb.Write((long)value);
break;
case (byte)TagType.Float:
mb.Write((float)value);
break;
case (byte)TagType.Double:
mb.Write((double)value);
break;
case (byte)TagType.String:
string sval = value.ToString();
//mb.Write(sval.Length);
mb.Write(sval, Encoding.Unicode);
break;
case (byte)TagType.DateTime:
mb.Write(((DateTime)value).Ticks);
break;
case (byte)TagType.IntPoint:
mb.Write(((IntPointData)value).X);
mb.Write(((IntPointData)value).Y);
break;
case (byte)TagType.UIntPoint:
mb.Write((int)((UIntPointData)value).X);
mb.Write((int)((UIntPointData)value).Y);
break;
case (byte)TagType.IntPoint3:
mb.Write(((IntPoint3Data)value).X);
mb.Write(((IntPoint3Data)value).Y);
mb.Write(((IntPoint3Data)value).Z);
break;
case (byte)TagType.UIntPoint3:
mb.Write((int)((UIntPoint3Data)value).X);
mb.Write((int)((UIntPoint3Data)value).Y);
mb.Write((int)((UIntPoint3Data)value).Z);
break;
case (byte)TagType.LongPoint:
mb.Write(((LongPointData)value).X);
mb.Write(((LongPointData)value).Y);
break;
case (byte)TagType.ULongPoint:
mb.Write((long)((ULongPointData)value).X);
mb.Write((long)((ULongPointData)value).Y);
break;
case (byte)TagType.LongPoint3:
mb.Write(((LongPoint3Data)value).X);
mb.Write(((LongPoint3Data)value).Y);
mb.Write(((LongPoint3Data)value).Z);
break;
case (byte)TagType.ULongPoint3:
mb.Write((long)((ULongPoint3Data)value).X);
mb.Write((long)((ULongPoint3Data)value).Y);
mb.Write((long)((ULongPoint3Data)value).Z);
break;
}
realSetRequreEvent.Reset();
SendData(mb);
if (realSetRequreEvent.WaitOne(timeout))
{
if (this.mRealSetResponseData.WriteIndex - mRealSetResponseData.ReadIndex > 0)
{
try
{
return mRealSetResponseData.ReadByte() > 0;
}
finally
{
mRealSetResponseData?.UnlockAndReturn();
}
}
else
{
return true;
}
}
return false;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public bool SetTagValue(List<int> id, List<byte> valueType, List<object> value, int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8 + 30);
mb.Write(ApiFunConst.SetDataValue);
mb.Write(this.LoginId);
mb.Write(1);
for (int i = 0; i < id.Count; i++)
{
mb.Write(id[i]);
switch (valueType[i])
{
case (byte)TagType.Bool:
mb.Write((byte)value[i]);
break;
case (byte)TagType.Byte:
mb.Write((byte)value[i]);
break;
case (byte)TagType.Short:
mb.Write((short)value[i]);
break;
case (byte)TagType.UShort:
mb.Write((ushort)value[i]);
break;
case (byte)TagType.Int:
mb.Write((int)value[i]);
break;
case (byte)TagType.UInt:
mb.Write((int)value[i]);
break;
case (byte)TagType.Long:
case (byte)TagType.ULong:
mb.Write((long)value[i]);
break;
case (byte)TagType.Float:
mb.Write((float)value[i]);
break;
case (byte)TagType.Double:
mb.Write((double)value[i]);
break;
case (byte)TagType.String:
string sval = value[i].ToString();
//mb.Write(sval.Length);
mb.Write(sval, Encoding.Unicode);
break;
case (byte)TagType.DateTime:
mb.Write(((DateTime)value[i]).Ticks);
break;
case (byte)TagType.IntPoint:
mb.Write(((IntPointData)value[i]).X);
mb.Write(((IntPointData)value[i]).Y);
break;
case (byte)TagType.UIntPoint:
mb.Write((int)((UIntPointData)value[i]).X);
mb.Write((int)((UIntPointData)value[i]).Y);
break;
case (byte)TagType.IntPoint3:
mb.Write(((IntPoint3Data)value[i]).X);
mb.Write(((IntPoint3Data)value[i]).Y);
mb.Write(((IntPoint3Data)value[i]).Z);
break;
case (byte)TagType.UIntPoint3:
mb.Write((int)((UIntPoint3Data)value[i]).X);
mb.Write((int)((UIntPoint3Data)value[i]).Y);
mb.Write((int)((UIntPoint3Data)value[i]).Z);
break;
case (byte)TagType.LongPoint:
mb.Write(((LongPointData)value[i]).X);
mb.Write(((LongPointData)value[i]).Y);
break;
case (byte)TagType.ULongPoint:
mb.Write((long)((ULongPointData)value[i]).X);
mb.Write((long)((ULongPointData)value[i]).Y);
break;
case (byte)TagType.LongPoint3:
mb.Write(((LongPoint3Data)value[i]).X);
mb.Write(((LongPoint3Data)value[i]).Y);
mb.Write(((LongPoint3Data)value[i]).Z);
break;
case (byte)TagType.ULongPoint3:
mb.Write((long)((ULongPoint3Data)value[i]).X);
mb.Write((long)((ULongPoint3Data)value[i]).Y);
mb.Write((long)((ULongPoint3Data)value[i]).Z);
break;
}
}
realRequreEvent.Reset();
SendData(mb);
try
{
if (realRequreEvent.WaitOne(timeout))
{
return mRealRequreData.ReadByte() > 0;
}
}
finally
{
mRealRequreData?.UnlockAndReturn();
mRealRequreData = null;
}
return false;
}
19
Source : DataFileManager.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void FileProcess()
{
List<KeyValuePair<string, WatcherChangeTypes>> ltmp = null;
string backupdatapath = GetBackHisDataPath();
while (!mIsClosed)
{
mResetEvent.WaitOne();
mResetEvent.Reset();
if (mIsClosed) break;
mResetCount = 0;
while (mResetCount<10)
{
Thread.Sleep(100);
mResetCount++;
}
if(mLogFileCach.Count>0)
{
lock(mLocker)
{
ltmp = mLogFileCach.ToList();
mLogFileCach.Clear();
}
foreach(var vv in ltmp)
{
LoggerService.Service.Info("DataFileMananger", "LogFile " + vv.Value + " add to FileCach!");
ParseLogFile(vv.Key);
}
}
if(mHisFileCach.Count>0)
{
lock (mLocker)
{
ltmp = this.mHisFileCach.ToList();
mHisFileCach.Clear();
}
foreach (var vv in ltmp)
{
var vifno = new System.IO.FileInfo(vv.Key);
if (vv.Value == System.IO.WatcherChangeTypes.Created)
{
LoggerService.Service.Info("DataFileMananger", "HisDataFile " + vv.Key + " is Created & will be add to dataFileCach!");
if (vifno.Extension == DataFileExtends)
{
ParseFileName(vifno);
}
}
else
{
LoggerService.Service.Info("DataFileMananger", "HisDataFile " + vv.Key + " is changed & will be processed!");
var vfile = CheckAndGetDataFile(vv.Key);
if (vfile != null)
{
backupdatapath = GetBackHisDataPath();
if (!string.IsNullOrEmpty(backupdatapath))
{
if(!vfile.FileName.StartsWith(backupdatapath))
{
vfile.UpdateLastDatetime();
}
}
else
{
vfile.UpdateLastDatetime();
}
}
else
{
if (vifno.Extension == DataFileExtends)
ParseFileName(vifno);
}
}
}
}
}
}
19
Source : RDDCClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ByteBuffer SyncRealData(int timeout=5000)
{
var mb = GetBuffer(RealDataSyncFun, 0);
mRealDataSyncEvent.Reset();
SendData(mb);
try
{
if (mRealDataSyncEvent.WaitOne(timeout))
{
return mRealDataSyncData;
}
}
finally
{
}
return null;
}
19
Source : RDDCClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public DateTime? GetStartTime(int timeout = 5000)
{
lock (mWorkStateLockObj)
{
var mb = GetBuffer(WorkStateFun, 1);
mb.WriteByte(GetStartTimeFun);
mWorkStateEvent.Reset();
SendData(mb);
try
{
if (mWorkStateEvent.WaitOne(timeout))
{
return DateTime.FromBinary(mWorkStateData.ReadLong());
}
}
finally
{
}
}
return null;
}
19
Source : RDDCClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public WorkState? GetWorkState(int timeout = 5000)
{
lock (mWorkStateLockObj)
{
var mb = GetBuffer(WorkStateFun, 1);
mb.WriteByte(GetStateFun);
mWorkStateEvent.Reset();
SendData(mb);
try
{
if (mWorkStateEvent.WaitOne(timeout))
{
return (WorkState)mWorkStateData.ReadByte();
}
}
finally
{
}
}
return null;
}
19
Source : RDDCClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public bool? SwitchToPrimary(int timeout = 5000)
{
lock (mWorkStateLockObj)
{
var mb = GetBuffer(WorkStateFun, 1);
mb.WriteByte(ChangeToPrimaryFun);
mWorkStateEvent.Reset();
SendData(mb);
try
{
if (mWorkStateEvent.WaitOne(timeout))
{
return mWorkStateData.ReadByte() > 0;
}
}
finally
{
}
}
return false;
}
19
Source : RDDCClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public bool? SwitchToStandby(int timeout = 5000)
{
lock (mWorkStateLockObj)
{
var mb = GetBuffer(WorkStateFun, 1);
mb.WriteByte(ChangeToStandbyFun);
mWorkStateEvent.Reset();
SendData(mb);
try
{
if (mWorkStateEvent.WaitOne(timeout))
{
return mWorkStateData.ReadByte() > 0;
}
}
finally
{
}
}
return false;
}
19
Source : NetTransformDriver.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void RemoteDataudpatePro()
{
while (!mIsClosed)
{
if (WorkMode == NetTransformWorkMode.Push)
{
resetEvent.WaitOne();
if (mIsClosed) break;
resetEvent.Reset();
if (mCachDatas != null)
{
int icount = mCachDatas.Count;
while (mCachDatas.Count > 0)
{
// ProcessSingleBufferData(mCachDatas.Dequeue());
ProcessBufferData(mCachDatas.Dequeue());
}
ValueUpdateEvent?.Invoke(this, null);
}
}
else
{
DateTime stime = DateTime.Now;
Client.SyncRealMemory(mSyncMemoryCach);
double span = (DateTime.Now - stime).TotalMilliseconds;
int sleeptime = span > PollCircle ? 1 : (int)(PollCircle - span);
ValueUpdateEvent?.Invoke(this, null);
Thread.Sleep(sleeptime);
}
}
}
19
Source : DatabaseRunner.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void MonitorThreadPro()
{
while(!mIsClosed)
{
resetEvent.WaitOne();
resetEvent.Reset();
if (mIsClosed) break;
if (mProxy.IsConnected)
{
try
{
string sname = mProxy.GetRunnerDatabase();
if (!string.IsNullOrEmpty(sname))
{
CheckAndLoadDatabase(sname);
}
else
{
Thread.Sleep(1000);
resetEvent.Set();
continue;
}
}
catch
{
Thread.Sleep(1000);
resetEvent.Set();
continue;
}
}
else
{
if (!string.IsNullOrEmpty(mDatabaseName))
{
CloseDatabase();
}
}
IsReadyEvent?.Invoke(mProxy.IsConnected);
Thread.Sleep(2000);
}
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public bool RegistorTagValueCallBack(int minid, int maxid, int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8 + 8);
mb.Write(ApiFunConst.RegistorValueCallback);
mb.Write(this.LoginId);
mb.Write(minid);
mb.Write(maxid);
this.realRequreEvent.Reset();
SendData(mb);
if (realRequreEvent.WaitOne(timeout))
{
try
{
return mRealRequreData.ReadByte() > 0;
}
finally
{
mRealRequreData?.UnlockAndReturn();
mRealRequreData = null;
}
}
return true;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public bool ClearRegistorTagValueCallBack(int timeout = 5000)
{
CheckLogin();
var mb = GetBuffer(ApiFunConst.RealDataRequestFun, 8 + 8);
mb.Write(ApiFunConst.ResetValueChangeNotify);
mb.Write(this.LoginId);
realRequreEvent.Reset();
SendData(mb);
if (realRequreEvent.WaitOne(timeout))
{
try
{
return mRealRequreData.ReadByte() > 0;
}
finally
{
mRealRequreData?.UnlockAndReturn();
mRealRequreData = null;
}
}
return true;
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ByteBuffer QueryAllHisValue(int id, DateTime startTime, DateTime endTime, int timeout = 5000)
{
var vid = 0;
ByteBuffer re = null;
lock (mHisDataLock)
{
vid = mHisRequreCount;
mHisRequreCount++;
CheckLogin();
}
var mb = GetBuffer(ApiFunConst.HisDataRequestFun, 8 + 20 + 4);
mb.Write(ApiFunConst.RequestAllHisData);
mb.Write(this.LoginId);
mb.Write(id);
mb.Write(startTime.Ticks);
mb.Write(endTime.Ticks);
mb.Write(vid);
ManualResetEvent hisRequreEvent = new ManualResetEvent(false);
hisRequreEvent.Reset();
lock (mHisDataCallBack)
{
mHisDataCallBack.Add(vid, (data) => {
re = data;
try
{
hisRequreEvent.Set();
}
catch
{
data?.UnlockAndReturn();
}
});
}
SendData(mb);
try
{
if (hisRequreEvent.WaitOne(timeout) && re != null && re.WriteIndex - re.ReadIndex > 1)
{
return re;
}
else
{
lock (mHisDataCallBack)
{
if (mHisDataCallBack.ContainsKey(vid))
{
mHisDataCallBack.Remove(vid);
}
else
{
return re;
}
}
}
return null;
}
finally
{
hisRequreEvent.Dispose();
}
}
19
Source : ApiClient.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ByteBuffer QueryStatisitcsValue(int id, DateTime startTime, DateTime endTime, int timeout = 5000)
{
var vid = 0;
ByteBuffer re = null;
lock (mHisDataLock)
{
vid = mHisRequreCount;
mHisRequreCount++;
CheckLogin();
}
var mb = GetBuffer(ApiFunConst.HisDataRequestFun, 8 + 20 + 4);
mb.Write(ApiFunConst.RequestNumberStatistics);
mb.Write(this.LoginId);
mb.Write(id);
mb.Write(startTime.Ticks);
mb.Write(endTime.Ticks);
mb.Write(vid);
ManualResetEvent hisRequreEvent = new ManualResetEvent(false);
hisRequreEvent.Reset();
lock (mHisDataCallBack)
{
mHisDataCallBack.Add(vid, (data) =>
{
re = data;
try
{
hisRequreEvent.Set();
}
catch
{
data?.UnlockAndReturn();
}
});
}
SendData(mb);
try
{
if (hisRequreEvent.WaitOne(timeout) && re != null && re.WriteIndex - re.ReadIndex > 1)
{
return re;
}
else
{
lock (mHisDataCallBack)
{
if (mHisDataCallBack.ContainsKey(vid))
{
mHisDataCallBack.Remove(vid);
}
else
{
return re;
}
}
}
return null;
}
finally
{
hisRequreEvent.Dispose();
}
}
19
Source : Driver.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void DateTimeThreadPro()
{
ThreadHelper.replacedignToCPU(CPUreplacedignHelper.Helper.CPUArray2);
List<Tagbase> vv = mTagIdCach.ContainsKey("Sim:datetime") ? mTagIdCach["Sim:datetime"] : null;
List<int> vvr = mManualRecordTagCach.ContainsKey("Sim:datetime") ? mManualRecordTagCach["Sim:datetime"] : null;
while (!mIsClosed)
{
mDatetimeEvent.WaitOne();
mDatetimeEvent.Reset();
if (mDatetimeReload)
{
vv = mTagIdCach.ContainsKey("Sim:datetime") ? mTagIdCach["Sim:datetime"] : null;
vvr = mManualRecordTagCach.ContainsKey("Sim:datetime") ? mManualRecordTagCach["Sim:datetime"] : null;
mDatetimeReload = false;
}
if (vv != null)
{
DateTime dnow = DateTime.Now;
mTagService.SetTagValue(vv,ref dnow, 0);
mTagService.SubmiteNotifyChanged();
}
if (vvr != null && vvr.Count > 0)
{
TagValue tv = new TagValue() { Quality = 0, Time = DateTime.UtcNow, Value = DateTime.Now };
foreach (var vvv in vvr)
{
mTagHisValueService.SetTagHisValue(vvv, tv);
}
}
var ts = (DateTime.Now - mLastProcessTime).TotalMilliseconds;
lock (mLockObj)
{
if (ts > mMaxProcessTimeSpan)
{
mMaxProcessTimeSpan = ts;
}
}
Interlocked.Increment(ref mFinishCount);
}
}
19
Source : RealDataServerProcess.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void SendThreadPro()
{
Tuple<int[], int> changtags;
while (!mIsClosed)
{
try
{
resetEvent.WaitOne();
if (mIsClosed) return;
resetEvent.Reset();
while (mChangedTags.Count > 0)
{
changtags = mChangedTags.Dequeue();
if (mCallBackRegistorIds.Count == 0)
{
ArrayPool<int>.Shared.Return(changtags.Item1);
break;
}
var clients = mCallBackRegistorIds.ToArray();
foreach (var cb in clients)
{
var buffer = Parent.Allocate(Api.ApiFunConst.RealDataPushFun, changtags.Item2 * 64+5);
buffer.Write(RealDataPush);
buffer.Write(0);
buffers.Add(cb.Key, buffer);
mDataCounts[cb.Key]= 0;
}
foreach (var vv in changtags.Item1)
{
foreach (var vvc in clients)
{
if (vvc.Value.Item2 || vvc.Value.Item1.Contains(vv))
{
ProcessTagPushByMemoryCopy(buffers[vvc.Key], vv);
mDataCounts[vvc.Key]++;
}
}
}
foreach (var cb in buffers)
{
//cb.Value.MarkWriterIndex();
//cb.Value.SetWriterIndex(2);
var ind = cb.Value.WriteIndex;
cb.Value.WriteIndex = 2;
cb.Value.Write(mDataCounts[cb.Key]);
cb.Value.WriteIndex = ind;
//cb.Value.WriteInt(mDataCounts[cb.Key]);
//cb.Value.ResetWriterIndex();
Parent.PushRealDatatoClient(cb.Key, cb.Value);
}
buffers.Clear();
ArrayPool<int>.Shared.Return(changtags.Item1);
}
if(mBlockCallBackRegistorIds.Count>0)
{
//Stopwatch sw = new Stopwatch();
//sw.Start();
int count = 0;
BlockItem vv;
while (mChangedBlocks.Count>0)
{
lock (mChangedBlocks)
vv = mChangedBlocks.Dequeue();
if (vv == null) continue;
var buffer = GetBlockSendBuffer2(vv);
foreach (var vvb in mBlockCallBackRegistorIds.ToArray())
{
// buffer.Retain();
Parent.PushRealDatatoClient(vvb.Key, buffer);
//buffer.ReleaseBuffer();
}
//while(buffer.ReferenceCount>0)
//buffer.ReleaseBuffer();
count++;
}
Thread.Sleep(10);
//sw.Stop();
//LoggerService.Service.Erro("RealDataServerProcess", "推送数据耗时" + sw.ElapsedMilliseconds + " 大小:" + count);
}
else
{
mChangedBlocks.Clear();
}
}
catch(Exception ex)
{
LoggerService.Service.Erro("RealDataServerProcess", ex.StackTrace);
}
}
}
19
Source : ServerProcessBase.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
private void DataProcess()
{
while (!mIsClosed)
{
resetEvent.WaitOne();
if (mIsClosed) return;
resetEvent.Reset();
try
{
foreach (var vv in mDatasCach)
{
while (vv.Value.Count > 0)
{
var dd = vv.Value.Dequeue();
if (dd != null)
ProcessSingleData(vv.Key, dd);
}
}
}
catch
{
}
}
}
See More Examples