Here are the examples of the csharp api System.Threading.Thread.Start(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
754 Examples
19
View Source File : RequestBridge.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public static void CreatePipeServers(int waiterCount)
{
Log.Verbose("Creating '{0}' pipe(s) connection waiter", waiterCount);
waiters = new Thread[waiterCount];
active = true;
for (int i = 0; i < waiters.Length; i++)
{
waiters[i] = new Thread(new ParameterizedThreadStart(RequestWaiter));
waiters[i].Start(null);
}
}
19
View Source File : RequestDispatcher.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public static bool CreateDispatchers(int dispatcherCount)
{
Thread tworker;
Log.Info("Creating {0} dispatcher worker", dispatcherCount);
_Active = true;
for (int i=0;i<dispatcherCount;i++)
{
tworker = new Thread(new ParameterizedThreadStart(DispatchWorker));
tworker.Start(null);
_Dispatchers.Add(tworker);
}
return true;
}
19
View Source File : PlatformFileDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
public DialogResult ShowDialog(IWin32Window owner)
{
DialogResult result = DialogResult.Cancel;
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
result = RunDialog(owner);
}
else
{
Thread staThread = new Thread(delegate (object state)
{
result = RunDialog((IWin32Window)state);
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start(owner);
staThread.Join();
}
return result;
}
19
View Source File : UdpClient.cs
License : MIT License
Project Creator : a11s
License : MIT License
Project Creator : a11s
public void Connect(IPEndPoint ipep, bool CreateBackgroundThread)
{
IOThreads.Clear();
lastHandshakeTime = DateTime.MinValue;
Incoming = new ConcurrentQueue<byte[]>();
Outgoing = new ConcurrentQueue<byte[]>();
udp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
bool bNewBehavior = false;
byte[] dwBytesReturned = new byte[4];
udp.IOControl((int)SIO_UDP_CONNRESET, BitConverter.GetBytes(bNewBehavior), dwBytesReturned);
}
defpb = new ServerPackBuilderEx(defpb.GetSysIdBuf(), SessionId);
remote_ipep = ipep;
udp.Connect(remote_ipep);
if (CreateBackgroundThread)
{
ioThread = new Thread(ioLoop);
ioThread.IsBackground = true;
ioThread.Name = $"{nameof(ioThread)}";
IOThreads.Add(ioThread.ManagedThreadId);
ioThread.Start();
}
debug?.Invoke($"start connect");
}
19
View Source File : Program.cs
License : MIT License
Project Creator : a11s
License : MIT License
Project Creator : a11s
[STAThread]
static void Main()
{
Console.WriteLine(Environment.OSVersion.Platform);
Console.WriteLine(Environment.OSVersion.VersionString);
Console.WriteLine("All test:");
Console.WriteLine("1 PureUdp test");
Console.WriteLine("2 PureKcp test");
Console.WriteLine("3 Udp+Kcp mix test");
Console.WriteLine("other: exit");
string input = "";
Console.WriteLine("input 1~3:");
input = Console.ReadLine();
switch (input.Trim())
{
case "0":
StartServer = StartServer0;
break;
case "1":
StartServer = StartServer1;
break;
case "2":
StartServer = StartServer2;
break;
case "3":
StartServer = StartServer3;
break;
default:
return;
break;
}
Console.Write("Input ip and port:");
var str = Console.ReadLine();
if (string.IsNullOrWhiteSpace(str))
{
str = "0.0.0.0:1000";
}
var arr = str.Split(":"[0]);
int port = 1000;
if (arr.Length > 1)
{
port = int.Parse(arr[1]);
}
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(arr[0]), port);
StartServer(ipep);
Console.WriteLine("Press ENTER to close");
Thread updatethread = new Thread(
() =>
{
SpinWait sw = new SpinWait();
while (App.ApplicationRunning)
{
Server?.Service();
sw.SpinOnce();
}
}
);
updatethread.IsBackground = true;
updatethread.Name = $"{nameof(updatethread)}";
updatethread.Start();
while (true)
{
var c = Console.ReadKey(false);
if (c.Key == ConsoleKey.Enter)
{
break;
}
}
Console.WriteLine("closing..");
Server?.Close(TimeSpan.FromSeconds(10));
var servertype = Server.GetType().Name;
Server?.Close(TimeSpan.FromSeconds(10));
Console.WriteLine($"Server {servertype} Closed. Press any to to exit");
Console.ReadKey();
}
19
View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
private void Initialize() {
this.workerThreads = new List<WorkerThread>();
for (int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = new WorkerThread();
workerThread.Thread = new Thread(new ParameterizedThreadStart(RunWorkerThread));
workerThread.Thread.Name = "worker " + i;
workerThreads.Add(workerThread);
workerThread.Thread.IsBackground = true;
workerThread.Thread.Start(i);
}
}
19
View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
private void Initialize() {
this.workerThreads = new List<WorkerThread>();
for(int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = new WorkerThread();
workerThread.Thread = new Thread(new ParameterizedThreadStart(RunWorkerThread));
workerThread.Thread.Name = "worker " + i;
workerThreads.Add(workerThread);
workerThread.Thread.IsBackground = true;
workerThread.Thread.Start(i);
}
}
19
View Source File : Parallel.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
private void Initialize()
{
this.workerThreads = new List<WorkerThread>();
for (int i = 0; i < this.threadCount; i++)
{
WorkerThread workerThread = new WorkerThread();
workerThread.Thread = new Thread(new ParameterizedThreadStart(RunWorkerThread));
workerThread.Thread.Name = "worker " + i;
workerThreads.Add(workerThread);
workerThread.Thread.IsBackground = true;
workerThread.Thread.Start(i);
}
}
19
View Source File : Model.cs
License : MIT License
Project Creator : advancedmonitoring
License : MIT License
Project Creator : advancedmonitoring
public static void ButtonFillRegistryClicked()
{
var dlg = new UIFolderRegPickerWindow(MW, false);
if (dlg.ShowDialog() ?? false)
{
var work = new Thread(RegistryFill);
var abortEvent = new ManualResetEvent(false);
var w = new UIPerformWorkWindow(MW, abortEvent, "Count reg-keys...");
work.Start(new Tuple<UIFolderRegPickerWindow, UIPerformWorkWindow>(dlg, w));
if (w.ShowDialog() ?? false)
{
MW.SetContent();
if (MW.CmbxRightsType.SelectedIndex != 4)
MW.CmbxRightsType.SelectedIndex = 4;
MW.SetContent(_fillData);
}
work.Join();
}
}
19
View Source File : Model.cs
License : MIT License
Project Creator : advancedmonitoring
License : MIT License
Project Creator : advancedmonitoring
public static void TextChangedContentEdit()
{
if (_textChangedThread != null && _textChangedThread.IsAlive)
{
TextChangedEvent.Set();
_textChangedThread.Join();
}
TextChangedEvent.Reset();
_textChangedThread = new Thread(TextChangedFunc);
_textChangedThread.Start(MW.GetContent());
_textChangedSpinnerThread = new Thread(TextChangedSpinnerFunc);
_textChangedSpinnerThread.Start();
}
19
View Source File : Model.cs
License : MIT License
Project Creator : advancedmonitoring
License : MIT License
Project Creator : advancedmonitoring
public static void ButtonFillServicesClicked()
{
var work = new Thread(ServiceFill);
var abortEvent = new ManualResetEvent(false);
var dlg = new UIPerformWorkWindow(MW, abortEvent, "Count services...");
work.Start(dlg);
if (dlg.ShowDialog() ?? false)
{
MW.SetContent();
if (MW.CmbxRightsType.SelectedIndex != 0)
MW.CmbxRightsType.SelectedIndex = 0;
MW.SetContent(_fillData);
}
work.Join();
}
19
View Source File : Model.cs
License : MIT License
Project Creator : advancedmonitoring
License : MIT License
Project Creator : advancedmonitoring
public static void ButtonFillDirectoryClicked()
{
var dlg = new UIFolderRegPickerWindow(MW, true);
if (dlg.ShowDialog() ?? false)
{
var work = new Thread(DirectoryFill);
var abortEvent = new ManualResetEvent(false);
var w = new UIPerformWorkWindow(MW, abortEvent, "Count directories...");
work.Start(new Tuple<UIFolderRegPickerWindow, UIPerformWorkWindow>(dlg, w));
if (w.ShowDialog() ?? false)
{
int target = 1;
if (dlg.IsFilesInclude)
target = 3;
MW.SetContent();
if (MW.CmbxRightsType.SelectedIndex != target)
MW.CmbxRightsType.SelectedIndex = target;
MW.SetContent(_fillData);
}
work.Join();
}
}
19
View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : advancedmonitoring
License : MIT License
Project Creator : advancedmonitoring
public void SetContent(string content = null)
{
var setContent = content ?? string.Empty;
if (setContent.Length < CONTENT_CHUNK_SIZE)
{
EdtContent.Text = setContent;
return;
}
EdtContent.TextChanged -= EdtContent_OnTextChanged;
var abortEvent = new ManualResetEvent(false);
var dlg = new UIPerformWorkWindow(this, abortEvent, "Displaying content", "Displaying content: {0,3}%");
Thread work = new Thread(ContentUpdate);
work.Start(new Tuple<string, UIPerformWorkWindow>(setContent, dlg));
dlg.ShowDialog();
work.Join();
}
19
View Source File : GuiderImpl.cs
License : MIT License
Project Creator : agalasso
License : MIT License
Project Creator : agalasso
public override void Connect()
{
Close();
ushort port = (ushort)(4400 + m_instance - 1);
if (!m_conn.Connect(m_host, port))
throw new GuiderException(String.Format("Could not connect to PHD2 instance {0} on {1}", m_instance, m_host));
m_terminate = false;
System.Threading.Thread thr = new System.Threading.Thread(Worker);
thr.Start(this);
m_worker = thr;
}
19
View Source File : ThreadSample.cs
License : The Unlicense
Project Creator : ahotko
License : The Unlicense
Project Creator : ahotko
public void Go()
{
var threadLabor = new ThreadLabor();
var laborInstructions = new LaborInstructions(syncObject)
{
SomeParameter = $"Current DateTime is {DateTime.Now.ToString()}"
};
Console.WriteLine("Going into thread...");
var thread = new Thread(threadLabor.DoWork)
{
Priority = ThreadPriority.Highest
};
thread.Start(laborInstructions);
syncObject.WaitOne();
Console.WriteLine("done!");
}
19
View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
public void RunBackground(Action action)
{
CurrentBackground = new BackgroundWindow();
var t = new System.Threading.Tasks.Task(new Action(() => {
try
{
action();
CurrentBackground.Closing -= CurrentBackground.OnClosing;
Dispatcher.Invoke(CurrentBackground.Close);
}
catch (Exception ex)
{
Dispatcher.Invoke(() => {
var ew = new ErrorWindow();
var tr = new Thread(new ParameterizedThreadStart(ew.ShowError))
{
CurrentCulture = new System.Globalization.CultureInfo("en-US"),
CurrentUICulture = new System.Globalization.CultureInfo("en-US")
};
tr.Start(ex);
if (ew.ShowDialog() != true)
{
CurrentBackground.Closing -= CurrentBackground.OnClosing;
Dispatcher.Invoke(() => {
CurrentBackground.Close();
Close();
});
}
});
}
}));
t.Start();
CurrentBackground.ShowDialog();
}
19
View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
public void OnUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
var ew = new ErrorWindow();
var t = new Thread(new ParameterizedThreadStart(ew.ShowError))
{
CurrentCulture = new System.Globalization.CultureInfo("en-US"),
CurrentUICulture = new System.Globalization.CultureInfo("en-US")
};
t.Start(e.Exception);
e.Handled = true;
if (ew.ShowDialog() != true)
{
if (CurrentBackground != null)
{
CurrentBackground.Closing -= CurrentBackground.OnClosing;
CurrentBackground.Close();
}
Close();
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Airkek
License : MIT License
Project Creator : Airkek
[STAThread]
static void Main(string[] args)
{
if (!File.Exists("proxy_url.txt"))
{
File.AppendAllText("proxy_url.txt", string.Join("\r\n", Urls));
}
Console.replacedle = $"YTBot | {gitRepo}";
Logo(ConsoleColor.Cyan);
id = dialog("Enter Video ID");
threadsCount = Convert.ToInt32(dialog("Enter Threads Count"));
while (true)
{
Logo(ConsoleColor.Cyan);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Select proxy type:\r\n1. Http/s\r\n2. Socks4\r\n3. Socks5");
Console.Write("Your choice: ");
Console.ForegroundColor = ConsoleColor.Cyan;
char k = Console.ReadKey().KeyChar;
try
{
int key = int.Parse(k.ToString());
switch (key)
{
case 1:
proxyType = ProxyType.HTTP;
break;
case 2:
proxyType = ProxyType.Socks4;
break;
case 3:
proxyType = ProxyType.Socks5;
break;
default:
throw new Exception();
}
}
catch
{
continue;
}
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"\r\nSelected {proxyType} proxy");
break;
}
while (true)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Update proxies by urls?:\r\n1. Yes\r\n2. No");
Console.Write("Your choice: ");
char k = Console.ReadKey().KeyChar;
try
{
int pt = int.Parse(k.ToString());
switch (pt)
{
case 1:
updateProxy = true;
break;
case 2:
break;
default:
throw new Exception();
}
}
catch
{
continue;
}
break;
}
if (updateProxy)
{
Urls = File.ReadAllText("proxy_url.txt").Trim().Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
Console.WriteLine("Proxy links: \r\n" + string.Join("\r\n", Urls));
Console.WriteLine("You can set your own links in 'proxy_url.txt' file");
string totalProxies = String.Empty;
foreach(string proxyUrl in Urls)
{
Console.WriteLine($"Downloading proxies from '{proxyUrl}'");
using (HttpRequest req = new HttpRequest())
{
totalProxies += req.Get(proxyUrl).ToString() + "\r\n";
}
}
scraper = new ProxyQueue(totalProxies, proxyType);
}
else
{
Console.WriteLine("Select proxy list");
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Proxy list (*.txt)|*.txt";
if (dialog.ShowDialog() != DialogResult.OK)
{
return;
}
scraper = new ProxyQueue(File.ReadAllText(dialog.FileName), proxyType);
}
Console.WriteLine($"Loaded {scraper.Length} proxies");
Logo(ConsoleColor.Green);
List<Thread> threads = new List<Thread>();
Thread logWorker = new Thread(Log);
logWorker.Start();
threads.Add(logWorker);
if (updateProxy)
{
Thread proxyWorker = new Thread(proxyUpdater);
proxyWorker.Start();
threads.Add(proxyWorker);
}
for (int i = 0; i < threadsCount; i++)
{
Thread t = new Thread(Worker);
t.Start();
threads.Add(t);
}
foreach (Thread t in threads)
t.Join();
Console.ReadKey();
}
19
View Source File : Counter.Tests.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[TestMethod]
public void TestGetUniqueNoConcurrency()
{
var counter = new Counter();
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
Thread t = new Thread(ThreadProc);
t.Start(counter);
threads[i] = t;
}
for(int i = 0; i < 3; i++)
{
threads[i].Join();
}
replacedert.AreEqual(3, counter.GetCurrent);
}
19
View Source File : KrakenX.cs
License : GNU General Public License v3.0
Project Creator : akmadian
License : GNU General Public License v3.0
Project Creator : akmadian
public void SetPumpSpeed(int Speed)
{
if (PumpOverrideThread != null)
PumpOverrideThread.Abort(); // I know it's bad code, but no other safe method works properly :/
if (true)
{
if (Speed > 100 || Speed < 50) {
throw new InvalidParamException("Pump speed percentages must be between 50-100 (inclusive).");
}
}
byte[] command = new byte[] { 0x02, 0x4d, 0x40, 0x00, Convert.ToByte(Speed) };
this.StopPumpOverrideLoop = false;
PumpOverrideThread = new Thread(new ParameterizedThreadStart(PumpSpeedOverrideLoop));
PumpOverrideThread.Start(command);
}
19
View Source File : KrakenX.cs
License : GNU General Public License v3.0
Project Creator : akmadian
License : GNU General Public License v3.0
Project Creator : akmadian
public void SetFanSpeed(int Percent)
{
if (FanOverrideThread != null)
FanOverrideThread.Abort(); // I know it's bad code, but no other safe method works properly :/
if (Percent > 100 || Percent < 25) {
throw new InvalidParamException("Fan speed percentage must be between 25-100 (inclusive).");
}
byte[] command = new byte[] { 0x02, 0x4d, 0x00, 0x00, Convert.ToByte(Percent) };
this.StopFanOverrideLoop = false;
FanOverrideThread = new Thread(new ParameterizedThreadStart(FanSpeedOverrideLoop));
FanOverrideThread.Start(command);
}
19
View Source File : SampleMultiThreading.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
void createRaycastThreads()
{
//// Create and start threads that will perform raycasts.
//// Create a sync for each thread so that a signal may be sent
//// from the main thread to the raycast thread that it can start
//// performing raycasts.
//for (PxU32 i=0; i < gNumThreads; ++i)
for (uint i = 0; i < gNumThreads; ++i)
{
gThreads[i] = new RaycastThread();
////Create a sync.
//gThreads[i].mWorkReadySyncHandle = SnippetUtils::syncCreate();
gThreads[i].mWorkReadySyncHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
////Create and start a thread.
//gThreads[i].mThreadHandle = SnippetUtils::threadCreate(threadExecute, &gThreads[i]);
gThreads[i].mThreadHandle = new Thread(threadExecute);
gThreads[i].mThreadHandle.Start(gThreads[i]);
}
//// Create another sync so that the raycast threads can signal to the main
//// thread that they have finished performing their raycasts.
//gWorkDoneSyncHandle = SnippetUtils::syncCreate();
gWorkDoneSyncHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
}
19
View Source File : TextureScaler.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
private static void ThreadedScale(Texture2D tex, int newWidth, int newHeight, bool useBilinear)
{
texColors = tex.GetPixels();
newColors = new Color[newWidth * newHeight];
if (useBilinear)
{
ratioX = 1.0f / ((float)newWidth / (tex.width - 1));
ratioY = 1.0f / ((float)newHeight / (tex.height - 1));
}
else {
ratioX = ((float)tex.width) / newWidth;
ratioY = ((float)tex.height) / newHeight;
}
w = tex.width;
w2 = newWidth;
#if WINDOWS_UWP
var cores = 1;
#else
var cores = Mathf.Min(SystemInfo.processorCount, newHeight);
#endif
var slice = newHeight / cores;
finishCount = 0;
if (mutex == null)
{
mutex = new Mutex(false);
}
#if WINDOWS_UWP
ThreadData threadData = new ThreadData(0, newHeight);
if (useBilinear)
{
BilinearScale(threadData);
}
else
{
PointScale(threadData);
}
#else
if (cores > 1)
{
int i = 0;
ThreadData threadData;
for (i = 0; i < cores - 1; i++)
{
threadData = new ThreadData(slice * i, slice * (i + 1));
ParameterizedThreadStart ts = useBilinear ? new ParameterizedThreadStart(BilinearScale) : new ParameterizedThreadStart(PointScale);
Thread thread = new Thread(ts);
thread.Start(threadData);
}
threadData = new ThreadData(slice * i, newHeight);
if (useBilinear)
{
BilinearScale(threadData);
}
else
{
PointScale(threadData);
}
while (finishCount < cores)
{
Thread.Sleep(1);
}
}
else
{
ThreadData threadData = new ThreadData(0, newHeight);
if (useBilinear)
{
BilinearScale(threadData);
}
else
{
PointScale(threadData);
}
}
#endif
tex.Resize(newWidth, newHeight);
tex.SetPixels(newColors);
tex.Apply();
texColors = null;
newColors = null;
}
19
View Source File : PDFExportProgress.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
public static void ShowAsync(Form parent)
{
showThread = new Thread(Run)
{
IsBackground = true,
Name = "PDFExporterProgressDialogShowThread"
};
Point point = parent == null
? new Point(Screen.PrimaryScreen.WorkingArea.Width/2, Screen.PrimaryScreen.WorkingArea.Height/2)
: new Point(parent.Left + parent.Width/2, parent.Top + parent.Height/2);
showThread.Start(point);
}
19
View Source File : BitMexClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void Connect()
{
if (_ws != null)
{
Disconnect();
}
_ws = new ClientWebSocket();
Uri uri = new Uri(_serverAdress);
_ws.ConnectAsync(uri, CancellationToken.None).Wait();
if (_ws.State == WebSocketState.Open)
{
if (Connected != null)
{
Connected.Invoke();
}
IsConnected = true;
}
Thread worker = new Thread(GetRes);
worker.CurrentCulture = new CultureInfo("ru-RU");
worker.IsBackground = true;
worker.Start(_ws);
Thread converter = new Thread(Converter);
converter.CurrentCulture = new CultureInfo("ru-RU");
converter.IsBackground = true;
converter.Start();
Thread wspinger = new Thread(_pinger);
wspinger.CurrentCulture = new CultureInfo("ru-RU");
wspinger.IsBackground = true;
wspinger.Start();
Auth();
}
19
View Source File : BitStampClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void Connect()
{
if (string.IsNullOrWhiteSpace(_apiKeyPublic) ||
string.IsNullOrWhiteSpace(_apiKeySecret) ||
string.IsNullOrWhiteSpace(_clientId))
{
return;
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
Uri uri = new Uri("https://www.bitstamp.net");
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch
{
LogMessageEvent("Сервер не доступен. Отсутствуюет интернет. ", LogMessageType.Error);
return;
}
IsConnected = true;
if (Connected != null)
{
Connected();
}
// start stream data through WebSocket / запускаем потоковые данные через WebSocket
_ws = new ClientWebSocket();
Uri wsUri = new Uri("wss://ws.bitstamp.net");
_ws.ConnectAsync(wsUri, CancellationToken.None).Wait();
if (_ws.State == WebSocketState.Open)
{
if (Connected != null)
{
Connected.Invoke();
}
IsConnected = true;
}
Thread worker = new Thread(GetRes);
worker.CurrentCulture = new CultureInfo("ru-RU");
worker.IsBackground = true;
worker.Start(_ws);
Thread converter = new Thread(Converter);
converter.CurrentCulture = new CultureInfo("ru-RU");
converter.IsBackground = true;
converter.Start();
}
19
View Source File : SampleLauncher.cs
License : MIT License
Project Creator : AliakseiFutryn
License : MIT License
Project Creator : AliakseiFutryn
static void CheckSingletonInMulreplacedhreadingMode()
{
Thread[] threads = new Thread[ThreadsCount];
Meeting[] meetings = new Meeting[ThreadsCount];
EventWaitHandle threadsFinishedEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
using (Barrier startBarrier = new Barrier(ThreadsCount), finishBarrier = new Barrier(ThreadsCount, barrier => threadsFinishedEvent.Set()))
{
for (int index = 0; index < ThreadsCount; index++)
{
threads[index] = new Thread(threadIndex =>
{
// Synchronizes all threads before start.
startBarrier.SignalAndWait();
try
{
int currentIndex = (int)threadIndex;
meetings[currentIndex] = currentIndex >= ThreadsCount / 2 ? DoubleCheckedSingleton<Meeting>.Instance : LazySingleton<Meeting>.Instance;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Synhronizes all threads before finish.
finishBarrier.SignalAndWait();
}
});
threads[index].Start(index);
}
threadsFinishedEvent.WaitOne();
Meeting lazySingletonInstance = LazySingleton<Meeting>.Instance;
Meeting doubleCheckedSingletonInstance = DoubleCheckedSingleton<Meeting>.Instance;
// There is an operation which is responsible for increasing some value of nearly
// created instances and then it should be compared with all other instances which
// were created in different threads.
lazySingletonInstance.ParticipantsCount++;
doubleCheckedSingletonInstance.ParticipantsCount++;
Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Take(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Skip(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
}
}
19
View Source File : WorkerThreadPool.cs
License : MIT License
Project Creator : AmplifyCreations
License : MIT License
Project Creator : AmplifyCreations
internal void InitializeAsyncUpdateThreads( int threadCount, bool systemThreadPool )
{
#if !NETFX_CORE && !UNITY_WEBGL
if ( systemThreadPool )
{
m_threadPoolFallback = true;
return;
}
try
{
m_threadPoolSize = threadCount;
m_threadStateQueues = new Queue<AmplifyMotion.MotionState>[ m_threadPoolSize ];
m_threadStateQueueLocks = new object[ m_threadPoolSize ];
m_threadPool = new Thread[ m_threadPoolSize ];
m_threadPoolTerminateSignal = new ManualResetEvent( false );
m_threadPoolContinueSignals = new AutoResetEvent[ m_threadPoolSize ];
m_threadPoolLock = new object();
m_threadPoolIndex = 0;
for ( int id = 0; id < m_threadPoolSize; id++ )
{
m_threadStateQueues[ id ] = new Queue<AmplifyMotion.MotionState>( ThreadStateQueueCapacity );
m_threadStateQueueLocks[ id ] = new object();
m_threadPoolContinueSignals[ id ] = new AutoResetEvent( false );
m_threadPool[ id ] = new Thread( new ParameterizedThreadStart( AsyncUpdateThread ) );
m_threadPool[ id ].Start( new KeyValuePair<object, int>( this, id ) );
}
}
catch ( Exception e )
{
// fallback to ThreadPool
Debug.LogWarning( "[AmplifyMotion] Non-critical error while initializing WorkerThreads. Falling back to using System.Threading.ThreadPool().\n" + e.Message );
m_threadPoolFallback = true;
}
#endif
}
19
View Source File : ProgressRunner.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public void Start(string caption)
{
Thread thread = new Thread(new ParameterizedThreadStart(this.Run));
ISvnClientPool pool = GetService<ISvnClientPool>();
IAnkhDialogOwner dialogOwner = GetService<IAnkhDialogOwner>();
using (ProgressDialog dialog = new ProgressDialog())
using (SvnClient client = pool.GetClient())
using (CreateUpdateReport ? BindOutputPane(client) : null)
using (dialog.Bind(client))
{
_sync = dialog;
dialog.Caption = caption;
dialog.Context = this;
thread.Name = "AnkhSVN Worker";
bool threadStarted = false;
dialog.HandleCreated += delegate
{
if (!threadStarted)
{
threadStarted = true;
thread.Start(client);
}
};
_invoker = dialog;
do
{
if (!_closed)
{
dialog.ShowDialog(this);
}
else
Application.DoEvents();
// Show the dialog again if the thread join times out
// Do this to handle the acase where the service wants to
// pop up a dialog before canceling.
// BH: Experienced this 2008-09-29 when our repository server
// accepted http connections but didn't handle them in time
}
while (!thread.Join(2500));
}
if (_cancelled)
{
// NOOP
}
else if (_exception != null)
throw new ProgressRunnerException(this._exception);
}
19
View Source File : TextureScale.cs
License : MIT License
Project Creator : anderm
License : MIT License
Project Creator : anderm
private static void ThreadedScale(Texture2D tex, int newWidth, int newHeight, bool useBilinear)
{
texColors = tex.GetPixels();
newColors = new Color[newWidth * newHeight];
if (useBilinear)
{
ratioX = 1.0f / ((float)newWidth / (tex.width - 1));
ratioY = 1.0f / ((float)newHeight / (tex.height - 1));
}
else
{
ratioX = ((float)tex.width) / newWidth;
ratioY = ((float)tex.height) / newHeight;
}
w = tex.width;
w2 = newWidth;
var cores = Mathf.Min(SystemInfo.processorCount, newHeight);
var slice = newHeight / cores;
finishCount = 0;
if (mutex == null)
{
mutex = new Mutex(false);
}
if (cores > 1)
{
int i = 0;
ThreadData threadData;
for (i = 0; i < cores - 1; i++)
{
threadData = new ThreadData(slice * i, slice * (i + 1));
ParameterizedThreadStart ts = useBilinear ? new ParameterizedThreadStart(BilinearScale) : new ParameterizedThreadStart(PointScale);
Thread thread = new Thread(ts);
thread.Start(threadData);
}
threadData = new ThreadData(slice * i, newHeight);
if (useBilinear)
{
BilinearScale(threadData);
}
else
{
PointScale(threadData);
}
while (finishCount < cores)
{
Thread.Sleep(1);
}
}
else
{
ThreadData threadData = new ThreadData(0, newHeight);
if (useBilinear)
{
BilinearScale(threadData);
}
else
{
PointScale(threadData);
}
}
tex.Resize(newWidth, newHeight, TextureFormat.RGB24, false);
tex.SetPixels(newColors);
tex.Apply();
texColors = null;
newColors = null;
}
19
View Source File : InstantPreviewManager.cs
License : Apache License 2.0
Project Creator : andijakl
License : Apache License 2.0
Project Creator : andijakl
private static IEnumerator InstallApkAndRunIfConnected(string adbPath, string localVersion)
{
string apkPath = null;
#if UNITY_EDITOR
apkPath = UnityEditor.replacedetDatabase.GUIDToreplacedetPath(k_ApkGuid);
#endif // !UNITY_EDITOR
// Early outs if set to install but the apk can't be found.
if (!File.Exists(apkPath))
{
Debug.LogError(
string.Format("Trying to install Instant Preview apk but reference to InstantPreview.apk is " +
"broken. Couldn't find an replacedet with .meta file guid={0}", k_ApkGuid));
yield break;
}
Result result = new Result();
Thread checkAdbThread = new Thread((object obj) =>
{
Result res = (Result)obj;
string output;
string errors;
// Gets version of installed apk.
RunAdbCommand(adbPath, "shell dumpsys package com.google.ar.core.instantpreview | grep versionName",
out output, out errors);
string installedVersion = null;
if (!string.IsNullOrEmpty(output) && string.IsNullOrEmpty(errors))
{
installedVersion = output.Substring(output.IndexOf('=') + 1);
}
// Early outs if no device is connected.
if (string.Compare(errors, k_NoDevicesFoundAdbResult) == 0)
{
return;
}
// Prints errors and exits on failure.
if (!string.IsNullOrEmpty(errors))
{
Debug.LogError(errors);
return;
}
if (installedVersion == null)
{
Debug.Log(string.Format(
"Instant Preview: app not found on device, attempting to install it from {0}.",
apkPath));
}
else if (installedVersion != localVersion)
{
Debug.Log(string.Format(
"Instant Preview: installed version \"{0}\" does not match local version \"{1}\", attempting upgrade.",
installedVersion, localVersion));
}
res.ShouldPromptForInstall = installedVersion != localVersion;
});
checkAdbThread.Start(result);
while (!checkAdbThread.Join(0))
{
yield return 0;
}
if (result.ShouldPromptForInstall)
{
if (PromptToInstall())
{
Thread installThread = new Thread(() =>
{
string output;
string errors;
RunAdbCommand(adbPath,
string.Format("uninstall com.google.ar.core.instantpreview", apkPath),
out output, out errors);
RunAdbCommand(adbPath,
string.Format("install \"{0}\"", apkPath),
out output, out errors);
// Prints any output from trying to install.
if (!string.IsNullOrEmpty(output))
{
Debug.Log(output);
}
if (!string.IsNullOrEmpty(errors))
{
if (string.Equals(errors, "Success"))
{
Debug.Log("Successfully installed Instant Preview app.");
}
else
{
Debug.LogError(errors);
}
}
});
installThread.Start();
while (!installThread.Join(0))
{
yield return 0;
}
}
else
{
yield break;
}
}
if (!NativeApi.IsConnected())
{
new Thread(() =>
{
string output;
string errors;
RunAdbCommand(adbPath,
"shell am start -n com.google.ar.core.instantpreview/.InstantPreviewActivity",
out output, out errors);
}).Start();
}
}
19
View Source File : UpdateMonitor.cs
License : GNU General Public License v3.0
Project Creator : Angelinsky7
License : GNU General Public License v3.0
Project Creator : Angelinsky7
private void M_Timer_Elapsed(object sender, ElapsedEventArgs e) {
if (!m_InCheckUpdate) {
m_InCheckUpdate = true;
try {
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() => {
NotifyCommandManager.CheckUpdate.Execute(new UpdateConfigCheck());
}));
thread.SetApartmentState(System.Threading.ApartmentState.STA);
thread.Start();
thread.Join();
thread = null;
} catch (Exception ex) { Console.WriteLine(ex.Message); }
m_InCheckUpdate = false;
}
}
19
View Source File : Parameter.cs
License : The Unlicense
Project Creator : Anirban166
License : The Unlicense
Project Creator : Anirban166
public static void Main()
{
Thread newThread = new Thread(pgm.work1);
newThread.Start(20);
pgm p = new pgm();
newThread = new Thread(p.work2);
newThread.Start("Instance");
Console.ReadLine();
}
19
View Source File : WeatherForecastController.cs
License : MIT License
Project Creator : anjoy8
License : MIT License
Project Creator : anjoy8
[HttpGet]
public WeatherForecast Get()
{
// 实例化一个对象实例
//WeatherForecast weather = WeatherForecast.GetInstance();
// 多线程去调用
for (int i = 0; i < 3; i++)
{
var th = new Thread(
new ParameterizedThreadStart((state) =>
{
//WeatherForecast.GetInstance();
// 此刻的心情
Console.WriteLine(_feeling.Date);
})
);
th.Start(i);
}
return null;
}
19
View Source File : VPOManager.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
public void Start(string filename, string mapname)
{
this.filename = filename;
this.mapname = mapname;
results.Clear();
// Start a thread on each core
threads = new Thread[dlls.Length];
for(int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(ProcessingThread);
threads[i].Priority = ThreadPriority.BelowNormal;
threads[i].Name = "Visplane Explorer " + i;
threads[i].Start(i);
}
}
19
View Source File : Utils.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd
License : Apache License 2.0
Project Creator : AnthonyLloyd
internal static void Run<T>(T concurrentState, (string, Action<T>)[] operations, int threads, int[] threadIds = null)
{
if (threadIds is null) threadIds = DummyArray;
Exception exception = null;
var opId = -1;
var runners = new Thread[threads];
while (--threads >= 0)
{
runners[threads] = new Thread(threadId =>
{
int i, tid = (int)threadId;
while ((i = Interlocked.Increment(ref opId)) < operations.Length)
{
threadIds[i] = tid;
try { operations[i].Item2(concurrentState); }
catch (Exception e)
{
if (exception is null)
{
exception = e;
Interlocked.Exchange(ref opId, operations.Length);
}
}
}
});
}
for (int i = 0; i < runners.Length; i++) runners[i].Start(i);
for (int i = 0; i < runners.Length; i++) runners[i].Join();
if (exception is not null) throw exception;
}
19
View Source File : Utils.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd
License : Apache License 2.0
Project Creator : AnthonyLloyd
internal static void RunReplay<T>(T concurrentState, (string, Action<T>)[] operations, int threads, int[] threadIds)
{
Exception exception = null;
var runners = new Thread[threads];
while (--threads >= 0)
{
runners[threads] = new Thread(threadId =>
{
int opId = -1, i = -1, tid = (int)threadId;
while ((i = Interlocked.Increment(ref opId)) < operations.Length)
{
if (threadIds[i] == tid)
{
try { operations[i].Item2(concurrentState); }
catch (Exception e)
{
if (exception is null)
{
exception = e;
Interlocked.Exchange(ref opId, operations.Length);
}
}
}
}
});
}
for (int i = 0; i < runners.Length; i++) runners[i].Start(i);
for (int i = 0; i < runners.Length; i++) runners[i].Join();
if (exception is not null) throw exception;
}
19
View Source File : ReverseComplementTests.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd
License : Apache License 2.0
Project Creator : AnthonyLloyd
public static int NotMain()
{
readCount = 0; lastPageSize = PAGE_SIZE; canWriteCount = 0; // not needed if not rerun
pages = new byte[1024][];
new Thread(() =>
{
static int Read(Stream stream, byte[] bytes, int offset)
{
var bytesRead = stream.Read(bytes, offset, PAGE_SIZE - offset);
return bytesRead + offset == PAGE_SIZE ? PAGE_SIZE
: bytesRead == 0 ? offset
: Read(stream, bytes, offset + bytesRead);
}
using var inStream = File.OpenRead(FastaUtils.Fasta.Filename);//Console.OpenStandardInput();
do
{
var page = ArrayPool<byte>.Shared.Rent(PAGE_SIZE);
lastPageSize = Read(inStream, page, 0);
pages[readCount] = page;
readCount++;
} while (lastPageSize == PAGE_SIZE);
}).Start();
new Thread(() =>
{
static void Reverse(object o)
{
Span<byte> map = stackalloc byte[256];
for (int b = 0; b < map.Length; b++) map[b] = (byte)b;
map['A'] = map['a'] = (byte)'T';
map['B'] = map['b'] = (byte)'V';
map['C'] = map['c'] = (byte)'G';
map['D'] = map['d'] = (byte)'H';
map['G'] = map['g'] = (byte)'C';
map['H'] = map['h'] = (byte)'D';
map['K'] = map['k'] = (byte)'M';
map['M'] = map['m'] = (byte)'K';
map['R'] = map['r'] = (byte)'Y';
map['T'] = map['t'] = (byte)'A';
map['V'] = map['v'] = (byte)'B';
map['Y'] = map['y'] = (byte)'R';
var (loPageID, lo, lastPageID, hi, previous) =
((int, int, int, int, Thread))o;
var hiPageID = lastPageID;
if (lo == PAGE_SIZE) { lo = 0; loPageID++; }
if (hi == -1) { hi = PAGE_SIZE - 1; hiPageID--; }
var loPage = pages[loPageID];
var hiPage = pages[hiPageID];
do
{
ref var loValue = ref loPage[lo++];
ref var hiValue = ref hiPage[hi--];
if (loValue == LF)
{
if (hiValue != LF) hi++;
}
else if (hiValue == LF)
{
lo--;
}
else
{
var swap = map[loValue];
loValue = map[hiValue];
hiValue = swap;
}
if (lo == PAGE_SIZE)
{
lo = 0;
loPage = pages[++loPageID];
if (previous == null || !previous.IsAlive)
canWriteCount = loPageID;
}
if (hi == -1)
{
hi = PAGE_SIZE - 1;
hiPage = pages[--hiPageID];
}
} while (loPageID < hiPageID
|| (loPageID == hiPageID && lo <= hi));
previous?.Join();
canWriteCount = lastPageID;
}
int pageID = 0, index = 0; Thread previous = null;
while (true)
{
while (true) // skip header
{
while (pageID == readCount) Thread.Sleep(0);
index = Array.IndexOf(pages[pageID], LF, index);
if (index != -1) break;
index = 0;
pageID++;
}
var loPageID = pageID;
var lo = ++index;
while (true)
{
while (pageID == readCount) Thread.Sleep(0);
var isLastPage = pageID + 1 == readCount && lastPageSize != PAGE_SIZE;
index = Array.IndexOf(pages[pageID], GT, index,
(isLastPage ? lastPageSize : PAGE_SIZE) - index);
if (index != -1)
{
object o = (loPageID, lo, pageID, index - 1, previous);
(previous = new Thread(Reverse)).Start(o);
break;
}
else if (isLastPage)
{
Reverse((loPageID, lo, pageID, lastPageSize - 1, previous));
canWriteCount = readCount;
return;
}
pageID++;
index = 0;
}
}
}).Start();
using var outStream = new CsCheck.HashStream(); //Console.OpenStandardOutput();
int writtenCount = 0;
while (true)
{
while (writtenCount == canWriteCount) Thread.Sleep(0);
var page = pages[writtenCount++];
if (writtenCount == readCount && lastPageSize != PAGE_SIZE)
{
outStream.Write(page, 0, lastPageSize);
return outStream.GetHashCode();
}
outStream.Write(page, 0, PAGE_SIZE);
ArrayPool<byte>.Shared.Return(page);
}
}
19
View Source File : ConsumerTest.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
[Test]
public void TestConsumerReceiveBeforeMessageDispatched(
[Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge,
AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)]
AcknowledgementMode ackMode)
{
// Launch a thread to perform a delayed send.
Thread sendThread = new Thread(DelayedProducerThreadProc);
using (IConnection connection = CreateConnection())
{
connection.Start();
using (ISession session = connection.CreateSession(ackMode))
{
ITemporaryQueue queue = session.CreateTemporaryQueue();
using (IMessageConsumer consumer = session.CreateConsumer(queue))
{
ThreadArg arg = new ThreadArg();
arg.connection = connection;
arg.session = session;
arg.destination = queue;
sendThread.Start(arg);
IMessage message = consumer.Receive(TimeSpan.FromMinutes(1));
replacedert.IsNotNull(message);
}
}
}
}
19
View Source File : NTRAPIFramework.cs
License : MIT License
Project Creator : architdate
License : MIT License
Project Creator : architdate
private void HandleDataReady(object sender, DataReadyEventArgs e)
{
// We move data processing to a separate thread. This way even if processing takes a long time, the netcode doesn't hang.
if (_waitingForData.TryGetValue(e.Seq, out DataReadyWaiting args))
{
Array.Copy(e.Data, args.Data, Math.Min(e.Data.Length, args.Data.Length));
Thread t = new(new ParameterizedThreadStart(args.Handler));
t.Start(args);
_waitingForData.Remove(e.Seq);
}
}
19
View Source File : MjpegStreamer.cs
License : MIT License
Project Creator : AristotelisChantzaras
License : MIT License
Project Creator : AristotelisChantzaras
public void Start(int port)
{
lock (this)
{
_Thread = new Thread(new ParameterizedThreadStart(ServerThread));
_Thread.IsBackground = true;
_Thread.Start(port);
}
}
19
View Source File : DriverHostForm.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative
public Thread DriverCommand(RequestData requestData)
{
try // Process the command
{
Application.DoEvents();
// Process the command on a separate thread allowing other requests to be handled concurrently through this thread, which is running the Windows message loop
Thread driverThread = new Thread(new ParameterizedThreadStart(ProcessCommand)); // Create a new thread on which to make the call to the COM driver
if (ServerForm.DebugTraceState) ServerForm.LogMessage1(requestData, requestData.Elements[ServerForm.URL_ELEMENT_METHOD], $"DriverCommand has received a command for {deviceKey} on FORM thread {Thread.CurrentThread.ManagedThreadId} Apartment state: {Thread.CurrentThread.GetApartmentState()} Is background: {Thread.CurrentThread.IsBackground} Is thread pool thread: {Thread.CurrentThread.IsThreadPoolThread}");
driverThread.Start(requestData); // Start the thread supplying the request data to the method
if (ServerForm.DebugTraceState) ServerForm.LogMessage1(requestData, requestData.Elements[ServerForm.URL_ELEMENT_METHOD], $"DriverCommand has started the command for {deviceKey} on FORM thread { Thread.CurrentThread.ManagedThreadId}");
return driverThread; // Return the thread so that the calling method can wait for it to complete and so that this thread can start waiting for the next command
}
catch (Exception ex) // Something serious has gone wrong with the ASCOM Remote server itself so report this to the user
{
ServerForm.LogException1(requestData, "DriverCommand", ex.ToString());
restServer.Return500Error(requestData, "Internal server error (DriverOnSeparateThread): " + ex.ToString());
}
return null;
}
19
View Source File : MailboxQueuesTests.cs
License : Apache License 2.0
Project Creator : asynkron
License : Apache License 2.0
Project Creator : asynkron
[Theory, InlineData(MailboxQueueKind.Unbounded)]
//[InlineData(MailboxQueueKind.Bounded)] -- temporarily disabled because the Bounded queue doesn't seem to work correctly
public void
Given_MailboxQueue_when_enqueue_and_dequeue_in_different_threads_Then_we_get_the_elements_in_the_FIFO_order(MailboxQueueKind kind)
{
const int msgCount = 1000;
var cancelSource = new CancellationTokenSource();
var sut = GetMailboxQueue(kind);
var producer = new Thread(
_ => {
for (var i = 0; i < msgCount; i++)
{
if (cancelSource.IsCancellationRequested) return;
sut.Push(i);
}
}
);
var consumerList = new List<int>();
var consumer = new Thread(
l => {
var list = (List<int>) l!;
for (var i = 0; i < msgCount; i++)
{
var popped = sut.Pop();
while (popped is null)
{
if (cancelSource.IsCancellationRequested) return;
Thread.Sleep(1);
popped = sut.Pop();
}
list.Add((int) popped);
}
}
);
producer.Start();
consumer.Start(consumerList);
producer.Join(1000);
consumer.Join(1000);
cancelSource.Cancel();
replacedert.Equal(msgCount, consumerList.Count);
for (var i = 0; i < msgCount; i++)
{
replacedert.Equal(i, consumerList[i]);
}
}
19
View Source File : WinHelper.cs
License : Microsoft Public License
Project Creator : atrenton
License : Microsoft Public License
Project Creator : atrenton
internal static void SendXmlToClipboard(string xml)
{
var t = new Thread(WinHelper.Clipboard_SetText);
t.SetApartmentState(ApartmentState.STA);
t.Start(xml);
}
19
View Source File : WaveFinder.cs
License : MIT License
Project Creator : AyrA
License : MIT License
Project Creator : AyrA
public static void FindAudio(Stream Input)
{
if (T != null)
{
throw new InvalidOperationException("Can't start a secondary scan process");
}
if (Input == null)
{
throw new ArgumentNullException(nameof(Input));
}
if (!Input.CanSeek)
{
throw new ArgumentException("Stream must be seekable", nameof(Input));
}
T = new Thread(Scanner);
T.Priority = ThreadPriority.BelowNormal;
T.IsBackground = true;
T.Start(Input);
}
19
View Source File : frmAudioExtract.cs
License : MIT License
Project Creator : AyrA
License : MIT License
Project Creator : AyrA
private void ScanSystem(string[] Root)
{
Log.Write("AudioExtract: Initialize system scanner");
mutex = new object();
Scan = true;
Found = false;
tbResourceFile.Enabled = false;
btnScan.Enabled = false;
btnSelectFile.Enabled = false;
ThreadCount = Root.Length;
SetText($"Scanning {ThreadCount} Drives...");
var d = (ParameterizedThreadStart)delegate (object o)
{
var Dirs = new Stack<string>();
Dirs.Push(o.ToString());
Log.Write("AudioExtract: System scanner {0} start", o);
while (Dirs.Count > 0 && Scan)
{
var Current = Dirs.Pop();
LastPath = Current;
try
{
var Pak = Path.Combine(Current, PAK_FILE);
if (File.Exists(Pak))
{
Log.Write("AudioExtract: System scanner {0} found {1}", o, Pak);
lock (mutex)
{
Scan = false;
Found = true;
Invoke((MethodInvoker)delegate
{
tbResourceFile.Enabled = true;
btnScan.Enabled = true;
btnSelectFile.Enabled = true;
OFD.FileName = Pak;
tbResourceFile.Text = Pak;
});
}
}
}
catch
{
//Ignore, probably no access
}
try
{
foreach (var SubDir in Directory.EnumerateDirectories(Current))
{
Dirs.Push(SubDir);
}
}
catch
{
Log.Write("AudioExtract: System scanner {0} couldn't enumerate {1}", o, Current);
//Ignore, probably no access
}
}
lock (mutex)
{
if (--ThreadCount == 0)
{
Invoke((MethodInvoker)delegate
{
SetText(null);
if (!Found)
{
MessageBox.Show($"Unable to find {PAK_FILE} on any of your harddrives.", "File scan", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
});
}
else
{
SetText($"Scanning {ThreadCount} Drives...");
}
Log.Write("AudioExtract: System scanner {0} ended", o);
}
};
foreach (var R in Root)
{
var T = new Thread(d);
T.IsBackground = true;
T.Start(R);
}
Thread TProgress = new Thread(delegate ()
{
while (Scan)
{
Invoke((MethodInvoker)delegate
{
lock (mutex)
{
tbResourceFile.Text = LastPath;
}
});
Thread.Sleep(500);
}
});
TProgress.IsBackground = true;
TProgress.Start();
}
19
View Source File : ImapBase.cs
License : Apache License 2.0
Project Creator : azanov
License : Apache License 2.0
Project Creator : azanov
internal bool StartIdling()
{
if (SelectedFolder == null)
return false;
switch (_idleState)
{
case IdleState.Off:
//if (SelectedFolder.UidNext == 0)
// SelectedFolder.Status(new[] { FolderStatusFields.UIdNext });
_lastIdleUId = SelectedFolder.UidNext;
break;
case IdleState.On:
return true;
case IdleState.Paused:
//if (SelectedFolder.UidNext == 0)
// SelectedFolder.Status(new[] { FolderStatusFields.UIdNext });
_lastIdleUId = SelectedFolder.UidNext;
break;
}
lock (_lock)
{
const string tmpl = "IMAPX{0} {1}";
_counter++;
string text = string.Format(tmpl, _counter, "IDLE") + "\r\n";
byte[] bytes = Encoding.UTF8.GetBytes(text.ToCharArray());
if (IsDebug)
Debug.WriteLine(text);
_ioStream.Write(bytes, 0, bytes.Length);
if (_ioStream.ReadByte() != '+')
return false;
var line = _streamReader.ReadLine();
if (IsDebug && !string.IsNullOrEmpty(line))
Debug.WriteLine(line);
}
_idleState = IdleState.On;
_idleLoopThread = new Thread(WaitForIdleServerEvents) {IsBackground = true};
_idleLoopThread.Start();
if (OnIdleStarted != null)
OnIdleStarted(SelectedFolder, new IdleEventArgs
{
Client = SelectedFolder.Client,
Folder = SelectedFolder
});
return true;
}
19
View Source File : ImapBase.cs
License : Apache License 2.0
Project Creator : azanov
License : Apache License 2.0
Project Creator : azanov
private void WaitForIdleServerEvents()
{
if (_idleProcessThread == null)
{
_idleProcessThread = new Thread(ProcessIdleServerEvents) {IsBackground = true};
_idleProcessThread.Start();
}
// a silent voice tells me to call that function from outside, but who cares
MaintainIdleConnection();
while (_idleState == IdleState.On)
{
if (_ioStream.ReadByte() != -1)
{
string tmp = _streamReader.ReadLine();
if (tmp == null)
continue;
if (IsDebug)
Debug.WriteLine(tmp);
if (tmp.ToUpper().Contains("OK IDLE COMPLETED") || tmp.ToUpper().Contains("TERMINATED"))
{
_idleState = IdleState.Off;
// unblock the processing thread, it will end itself because _idleState is Off
_idleEventsResetEvent.Set();
return;
}
_idleEvents.Enqueue(tmp);
// signal the waiting event processing thread to continue
_idleEventsResetEvent.Set();
if (_idleProcessThread != null && _idleProcessThread.ThreadState == ThreadState.Stopped)
_idleProcessThread = null;
if (_idleProcessThread == null)
{
_idleProcessThread = new Thread(ProcessIdleServerEvents) {IsBackground = true};
_idleProcessThread.Start();
}
}
//Thread.Sleep(5000);
}
}
19
View Source File : FrmConnect.cs
License : Apache License 2.0
Project Creator : azanov
License : Apache License 2.0
Project Creator : azanov
private void wbrMain_DoreplacedentCompleted(object sender, WebBrowserDoreplacedentCompletedEventArgs e)
{
try
{
_oAuth2Code = "";
if (_authMode == AuthMode.Google)
{
HtmlElement element = wbrMain.Doreplacedent.GetElementById("code");
if (element == null) return;
_oAuth2Code = element.GetAttribute("value");
}
else if (_authMode == AuthMode.Outlook && wbrMain.Url.ToString().StartsWith(OutlookOAuth2Provider.REDIRECT_URI)) {
var match = _rexCode.Match(wbrMain.Url.Query);
if (match.Success)
{
_oAuth2Code = match.Groups[1].Value;
}
}
else if (_authMode == AuthMode.Yahoo && wbrMain.Url.ToString().StartsWith(YahooOAuth2Provider.REDIRECT_URI))
{
var match = _rexCode.Match(wbrMain.Url.Query);
if (match.Success)
{
_oAuth2Code = match.Groups[1].Value;
}
}
if (!string.IsNullOrWhiteSpace(_oAuth2Code))
{
wbrMain.Hide();
lblWait.Text = "Connecting...";
lblWait.Show();
btnDefaultAuth.Hide();
InitClient();
(new Thread(Connect)).Start(true);
}
}
catch
{
}
}
19
View Source File : FrmConnect.cs
License : Apache License 2.0
Project Creator : azanov
License : Apache License 2.0
Project Creator : azanov
private void btnSignIn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(cmbServer.Text))
MessageBox.Show("Server cannot be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else if (string.IsNullOrEmpty(cmbPort.Text))
MessageBox.Show("Port cannot be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else if (string.IsNullOrEmpty(txtLogin.Text))
MessageBox.Show("Login cannot be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else if (string.IsNullOrEmpty(txtPreplacedword.Text))
MessageBox.Show("Preplacedword cannot be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
pnlLogin.Hide();
lblWait.Text = "Connecting...";
lblWait.Show();
picGMailLogin.Hide();
picOutlook.Hide();
picYahoo.Hide();
btnDefaultAuth.Hide();
InitClient();
(new Thread(Connect)).Start(false);
}
}
See More Examples