Here are the examples of the csharp api System.Threading.Thread.Join() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1042 Examples
19
Source : LogService.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static void Stop()
{
running = false;
sock.Close();
sock.Dispose();
logFile.Dispose();
worker.Join();
}
19
Source : RequestBridge.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static void Shutdown()
{
active = false;
Log.Info("Bridge shutting down op signalled");
AbortBlockingWaitOfPipeServer(waiters.Length);
foreach (Thread tworker in waiters)
{
Log.Verbose("T#{0} Waiting worker to finish",tworker.ManagedThreadId);
tworker.Join();
}
waiters = null;
}
19
Source : RequestDispatcher.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static void Shutdown()
{
_Active = false;
Log.Info("waiting dispatchers to finish");
foreach (Thread t in _Dispatchers)
{
t.Join();
}
Log.Info("all dispatchers finished their jobs");
_Dispatchers.Clear();
}
19
Source : CelesteNetClientModule.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void Start() {
if (_StartThread?.IsAlive ?? false)
_StartThread.Join();
lock (ClientLock) {
CelesteNetClientContext last = Context ?? ContextLast;
if (Client?.IsAlive ?? false)
Stop();
last?.Status?.Set(null);
Context = new(Celeste.Instance);
ContextLast = Context;
Context.Status.Set("Initializing...");
}
_StartThread = new(() => {
CelesteNetClientContext context = Context;
try {
context.Init(Settings);
context.Status.Set("Connecting...");
context.Start();
if (context.Status.Spin)
context.Status.Set("Connected", 1f);
} catch (ThreadInterruptedException) {
Logger.Log(LogLevel.CRI, "clientmod", "Startup interrupted.");
_StartThread = null;
Stop();
context.Status.Set("Interrupted", 3f, false);
} catch (ThreadAbortException) {
_StartThread = null;
Stop();
} catch (Exception e) {
Logger.Log(LogLevel.CRI, "clientmod", $"Failed connecting:\n{e}");
_StartThread = null;
Stop();
context.Status.Set("Connection failed", 3f, false);
} finally {
_StartThread = null;
}
}) {
Name = "CelesteNet Client Start",
IsBackground = true
};
_StartThread.Start();
}
19
Source : CelesteNetClientModule.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void Stop() {
QueuedTaskHelper.Cancel("CelesteNetAutoReconnect");
if (_StartThread?.IsAlive ?? false)
_StartThread.Join();
lock (ClientLock) {
if (Context == null)
return;
ContextLast = Context;
Context.Dispose();
Context = null;
}
}
19
Source : GmicConfigDialog.cs
with GNU General Public License v3.0
from 0xC0000054
with GNU General Public License v3.0
from 0xC0000054
private void GmicThreadFinished(DialogResult result)
{
workerThread.Join();
workerThread = null;
if (result == DialogResult.OK)
{
DialogResult = ProcessOutputImages();
}
else
{
DialogResult = DialogResult.Cancel;
}
Close();
}
19
Source : PlatformFileDialog.cs
with GNU General Public License v3.0
from 0xC0000054
with GNU General Public License v3.0
from 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
Source : Program.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
internal static async Task Main(string[] args)
{
try
{
if (args.Length == 0)
{
Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
var isFirstChar = true;
var completedPath = false;
var path = new StringBuilder();
do
{
var keyInfo = Console.ReadKey(true);
if (isFirstChar)
{
isFirstChar = false;
if (keyInfo.KeyChar != '"')
return;
}
else
{
if (keyInfo.KeyChar == '"')
{
completedPath = true;
args = new[] {path.ToString()};
}
else
path.Append(keyInfo.KeyChar);
}
} while (!completedPath);
Console.Clear();
}
Console.OutputEncoding = new UTF8Encoding(false);
Console.replacedle = replacedle;
Console.CursorVisible = false;
Console.WriteLine("Scanning for PKGs...");
var pkgList = new List<FileInfo>();
Console.ForegroundColor = ConsoleColor.Yellow;
foreach (var item in args)
{
var path = item.Trim('"');
if (File.Exists(path))
pkgList.Add(new FileInfo(path));
else if (Directory.Exists(path))
pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
else
Console.WriteLine("Unknown path: " + path);
}
Console.ResetColor();
if (pkgList.Count == 0)
{
Console.WriteLine("No packages were found. Check paths, and try again.");
return;
}
var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
var sigWidth = Math.Max(HeaderSignature.Length, 8);
var csumWidth = Math.Max(HeaderChecksum.Length, 5);
var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
var idealWidth = longestFilename + csumsWidth;
try
{
if (idealWidth > Console.LargestWindowWidth)
{
longestFilename = Console.LargestWindowWidth - csumsWidth;
idealWidth = Console.LargestWindowWidth;
}
if (idealWidth > Console.WindowWidth)
{
Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
Console.WindowWidth = idealWidth;
}
Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
}
catch (PlatformNotSupportedException) { }
Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
var t = new Thread(() =>
{
try
{
var indicatorIdx = 0;
while (!cts.Token.IsCancellationRequested)
{
Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
if (cts.Token.IsCancellationRequested)
return;
PkgChecker.Sync.Wait(cts.Token);
try
{
var frame = Animation[(indicatorIdx++) % Animation.Length];
var currentProgress = PkgChecker.CurrentFileProcessedBytes;
Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
if (PkgChecker.CurrentPadding > 0)
{
Console.CursorVisible = false;
var (top, left) = (Console.CursorTop, Console.CursorLeft);
Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
Console.CursorTop = top;
Console.CursorLeft = left;
Console.CursorVisible = false;
}
}
finally
{
PkgChecker.Sync.Release();
}
}
}
catch (TaskCanceledException)
{
}
});
t.Start();
await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
cts.Cancel(false);
t.Join();
}
finally
{
Console.replacedle = replacedle;
Console.WriteLine("Press any key to exit");
Console.ReadKey();
Console.WriteLine();
Console.CursorVisible = true;
}
}
19
Source : Form1.cs
with Mozilla Public License 2.0
from 1M50RRY
with Mozilla Public License 2.0
from 1M50RRY
private void button3_Click(object sender, EventArgs e)
{
//Crypt
string result = Properties.Resources.stub;
result = result.Replace("%startup%", startup.Checked.ToString().ToLower());
result = result.Replace("%native%", native.Checked.ToString().ToLower());
result = result.Replace("%selfinj%", si.Checked.ToString().ToLower());
result = result.Replace("%antivm%", antivm.Checked.ToString().ToLower());
result = result.Replace("%key%", key.Text);
result = result.Replace("%asm%", GenerateKey());
var providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v4.0"}
};
CompilerResults results;
using (var provider = new CSharpCodeProvider(providerOptions))
{
var Params = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, Environment.GetEnvironmentVariable("temp") + "\\Crypted.exe", true);
if (ico != null)
Params.CompilerOptions = "/t:winexe /unsafe /platform:x86 /win32icon:\"" + ico + "\"";
else
Params.CompilerOptions = "/t:winexe /unsafe /platform:x86";
Params.Referencedreplacedemblies.Add("System.Windows.Forms.dll");
Params.Referencedreplacedemblies.Add("System.dll");
Params.Referencedreplacedemblies.Add("System.Drawing.Dll");
Params.Referencedreplacedemblies.Add("System.Security.Dll");
Params.Referencedreplacedemblies.Add("System.Management.dll");
string fname = "";
if (punp.Checked)
{
fname = Pump();
Params.EmbeddedResources.Add(fname);
}
string tmp = "payload";
File.WriteAllBytes(tmp, EncryptAES(encFile, key.Text));
Params.EmbeddedResources.Add(tmp);
results = provider.CompilereplacedemblyFromSource(Params, result);
try
{
File.Delete(tmp);
File.Delete(fname);
}
catch(Exception)
{
}
}
if (results.Errors.Count == 0)
{
String temp = Environment.GetEnvironmentVariable("temp");
if (obf.Checked)
{
File.WriteAllBytes(temp + "\\cli.exe", Properties.Resources.cli);
File.WriteAllBytes(temp + "\\Confuser.Core.dll", Properties.Resources.Confuser_Core);
File.WriteAllBytes(temp + "\\Confuser.DynCipher.dll", Properties.Resources.Confuser_DynCipher);
File.WriteAllBytes(temp + "\\Confuser.Protections.dll", Properties.Resources.Confuser_Protections);
File.WriteAllBytes(temp + "\\Confuser.Renamer.dll", Properties.Resources.Confuser_Renamer);
File.WriteAllBytes(temp + "\\Confuser.Runtime.dll", Properties.Resources.Confuser_Runtime);
File.WriteAllBytes(temp + "\\dnlib.dll", Properties.Resources.dnlib);
String crproj = Properties.Resources.def.Replace("%out%", Environment.CurrentDirectory);
crproj = crproj.Replace("%base%", temp);
crproj = crproj.Replace("%file%", temp + "\\Crypted.exe");
File.WriteAllText(temp + "\\def.crproj", crproj);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = "/C " + temp + "\\cli.exe " + temp + "\\def.crproj";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = true;
startInfo.FileName = "cmd.exe";
Thread pr = new Thread(() => Process.Start(startInfo));
pr.Start();
pr.Join();
}
else
{
String file = Environment.CurrentDirectory + "\\Crypted.exe";
try
{
File.Delete(file);
}
catch(Exception)
{
}
File.Move(temp + "\\Crypted.exe", file);
}
MessageBox.Show("Done! Check Crypted.exe in the same folder.", "Crypting", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
foreach (CompilerError compilerError in results.Errors)
{
MessageBox.Show(string.Format("Error: {0}, At line {1}", compilerError.ErrorText, compilerError.Line));
}
}
19
Source : ProduceConsumeBufferTest.cs
with MIT License
from 39M
with MIT License
from 39M
[Test]
[Timeout(1000)]
public void Test() {
Thread consumer = new Thread(new ThreadStart(consumerThread));
Thread producer = new Thread(new ThreadStart(producerThread));
consumer.Start();
producer.Start();
consumer.Join();
producer.Join();
}
19
Source : Machine.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
public void Disconnect()
{
if (Log != null)
Log.Close();
Log = null;
Connected = false;
WorkerThread.Join();
try
{
Connection.Close();
}
catch { }
Connection.Dispose();
Connection = null;
Mode = OperatingMode.Disconnected;
MachinePosition = new Vector3();
WorkOffset = new Vector3();
FeedRateRealtime = 0;
CurrentTLO = 0;
if (PositionUpdateReceived != null)
PositionUpdateReceived.Invoke();
Status = "Disconnected";
DistanceMode = ParseDistanceMode.Absolute;
Unit = ParseUnit.Metric;
Plane = ArcPlane.XY;
BufferState = 0;
FeedOverride = 100;
RapidOverride = 100;
SpindleOverride = 100;
if (OverrideChanged != null)
OverrideChanged.Invoke();
PinStateLimitX = false;
PinStateLimitY = false;
PinStateLimitZ = false;
PinStateProbe = false;
if (PinStateChanged != null)
PinStateChanged.Invoke();
ToSend.Clear();
ToSendPriority.Clear();
Sent.Clear();
ToSendMacro.Clear();
}
19
Source : LogManager.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
public void Dispose()
{
if (!_isRunning)
return;
_isRunning = false;
_pool.Clear();
_writeThread.Join();
_pool.Clear();
if (_pool.IsAnyItemAcquired())
Thread.Sleep(100); // Can't really do much better here
_configResolver.Dispose();
_bufferSegmentProvider.Dispose();
}
19
Source : SerializedShardDatabase.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void Stop()
{
_queue.CompleteAdding();
_workerThread.Join();
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void Terminate() {
this.taskWaiting.Set();
this.thread.Join();
this.taskWaiting.Close();
this.threadIdle.Close();
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void Terminate() {
this.taskWaiting.Set();
this.thread.Join();
this.taskWaiting.Close();
this.threadIdle.Close();
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void Terminate()
{
this.taskWaiting.Set();
this.thread.Join();
this.taskWaiting.Close();
this.threadIdle.Close();
}
19
Source : Model.cs
with MIT License
from advancedmonitoring
with MIT License
from 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
Source : Model.cs
with MIT License
from advancedmonitoring
with MIT License
from 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
Source : MainWindow.xaml.cs
with MIT License
from advancedmonitoring
with MIT License
from 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
Source : Model.cs
with MIT License
from advancedmonitoring
with MIT License
from 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
Source : Model.cs
with MIT License
from advancedmonitoring
with MIT License
from advancedmonitoring
private static void TextChangedFunc(object o)
{
var data = (string)o;
var lines = data.Split('\r', '\n');
var allSIDs = new List<string>();
var allRights = new List<string>();
var prevSids = 0;
var prevRights = 0;
foreach (var line in lines)
{
if (!string.IsNullOrWhiteSpace(line))
{
var sd = new SecurityDescriptor(line.Trim());
if (!sd.IsOk)
continue;
var lSIDs = sd.GetAllSIDs();
foreach (var sid in lSIDs)
if (!allSIDs.Contains(sid))
allSIDs.Add(sid);
var lRights = sd.GetAllRights();
foreach (var right in lRights)
if (!allRights.Contains(right))
allRights.Add(right);
if (allSIDs.Count != prevSids)
{
prevSids = allSIDs.Count;
var sortedSIDs = allSIDs.OrderBy(q => q[1] == '-' ? "ZZ" + q : q).ToList();
MW.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<List<string>>((x) =>
{
MW.SIDList.Clear();
foreach (var sid in x)
MW.SIDList.Add(new BoolStringClreplaced(SecurityDescriptor.SIDToLong(sid, MW.IsTranslateSID), sid));
}), sortedSIDs);
}
if (allRights.Count != prevRights)
{
prevRights = allRights.Count;
MW.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
var newRightsList = new ObservableCollection<BoolStringClreplaced>();
foreach (var element in MW.RightsList)
{
if (allRights.Contains(element.Tag))
element.TextBrush = new SolidColorBrush(Color.FromRgb(50, 150, 255));
newRightsList.Add(element);
}
MW.RightsList.Clear();
foreach (var element in newRightsList)
MW.RightsList.Add(element);
}));
}
}
if (TextChangedEvent.WaitOne(0))
{
if (_textChangedSpinnerThread != null && _textChangedSpinnerThread.IsAlive)
_textChangedSpinnerThread.Join();
Thread.CurrentThread.Abort();
return;
}
}
TextChangedEvent.Set();
if (_textChangedSpinnerThread != null && _textChangedSpinnerThread.IsAlive)
_textChangedSpinnerThread.Join();
Thread.CurrentThread.Abort();
}
19
Source : Model.cs
with MIT License
from advancedmonitoring
with MIT License
from 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
Source : SimpleLooper.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public void ShutDown()
{
var toJoin = new Queue<Thread>();
for (int i = workers.Count - 1; i >= 0; i--)
{
lock (workers)
{
toJoin.Enqueue(workers[i].Thread);
workers[i].EnqueueTask(null, null);
}
}
while (toJoin.Count > 0)
{
toJoin.Dequeue().Join();
}
}
19
Source : GuiderImpl.cs
with MIT License
from agalasso
with MIT License
from agalasso
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (m_worker != null)
{
m_terminate = true;
m_conn.Terminate();
m_worker.Join();
m_worker = null;
}
m_conn.Close();
}
}
19
Source : ZThread.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public virtual void Join()
{
EnsureNotDisposed();
if (_thread == null) return;
_thread.Join();
}
19
Source : ZThread.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public virtual void Close()
{
EnsureNotDisposed();
Stop();
_thread?.Join();
}
19
Source : WaveOut.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Dispose()
{
if (m_Thread != null)
try
{
m_Finished = true;
if (m_WaveOut != IntPtr.Zero)
WaveNative.waveOutReset(m_WaveOut);
m_Thread.Join();
m_FillProc = null;
FreeBuffers();
if (m_WaveOut != IntPtr.Zero)
WaveNative.waveOutClose(m_WaveOut);
}
finally
{
m_Thread = null;
m_WaveOut = IntPtr.Zero;
}
//GC.SuppressFinalize(this);
}
19
Source : OpenFileDialog.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
[ContextMethod("ПоказатьДиалог", "ShowDialog")]
public IValue ShowDialog()
{
int Res1 = 0;
var thread = new Thread(() => Res1 = (int)Base_obj.ShowDialog());
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return ValueFactory.Create(Res1);
}
19
Source : FontDialog.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
[ContextMethod("ПоказатьДиалог", "ShowDialog")]
public IValue ShowDialog()
{
int Res1 = 0;
var thread = new Thread(() =>
{
Base_obj.ShowColor = true;
Res1 = (int)Base_obj.ShowDialog();
}
);
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return ValueFactory.Create(Res1);
}
19
Source : InputBox.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
[ContextMethod("Показать", "Show")]
public string Show(string p1, string p2, string p3 = "", int p4 = -1, int p5 = -1)
{
string str1 = "";
var thread = new Thread(() =>
{
str1 = Microsoft.VisualBasic.Interaction.InputBox(p1, p2, p3, p4, p5);
}
);
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return str1;
}
19
Source : Clipboard.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
[ContextMethod("ПолучитьИзображение", "GetImage")]
public ClBitmap GetImage()
{
ClBitmap ClBitmap1 = null;
var thread = new Thread(() =>
{
if (Clipboard.ContainsImage())
{
Bitmap Bitmap1 = new Bitmap((System.Drawing.Image)Clipboard.GetImage());
ClBitmap1 = new ClBitmap(Bitmap1);
}
}
);
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return ClBitmap1;
}
19
Source : Clipboard.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
[ContextMethod("ПолучитьТекст", "GetText")]
public string GetText()
{
string str1 = null;
var thread = new Thread(() =>
{
IDataObject dataObject = Clipboard.GetDataObject();
if (dataObject.GetDataPresent(DataFormats.UnicodeText))
{
str1 = (String)dataObject.GetData(DataFormats.UnicodeText);
}
}
);
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return str1;
}
19
Source : Clipboard.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
[ContextMethod("УстановитьИзображение", "SetImage")]
public void SetImage(ClBitmap bitmap)
{
var data = new DataObject();
data.SetData(DataFormats.Bitmap, true, ((System.Drawing.Image)(bitmap.Base_obj.M_Image)));
var thread = new Thread(() => Clipboard.SetDataObject(data, true));
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
19
Source : Clipboard.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
[ContextMethod("УстановитьТекст", "SetText")]
public void SetText(string text)
{
var data = new DataObject();
data.SetData(DataFormats.UnicodeText, true, text);
var thread = new Thread(() => Clipboard.SetDataObject(data, true));
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
19
Source : Counter.Tests.cs
with MIT License
from AiursoftWeb
with MIT License
from 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
Source : AtomicQueues.cs
with MIT License
from aksyr
with MIT License
from aksyr
[Test]
[TestCase(AllocationMode.Ephemeral)]
[TestCase(AllocationMode.Pooled)]
public void PreservesItems_WithSimultaneousQueueDequeue(AllocationMode allocationMode)
{
using (var queue = AtomicQueue<int>.Create(allocationMode))
{
var count = 0;
var allItems = new HashSet<int>();
var foundItems = new HashSet<int>();
var threads = new List<Thread>();
for (int i = 0; i < kWorkerCount; ++i)
{
allItems.Add(i + 1);
var thread = new Thread((o) =>
{
try
{
var item = Interlocked.Increment(ref count);
queue.Enqueue((int*)item);
}
catch (Exception e)
{
Debug.LogException(e);
}
});
thread.Start();
threads.Add(thread);
if (queue.TryDequeue(out var result))
foundItems.Add((int) result);
}
foreach (var thread in threads)
thread.Join();
while (foundItems.Count < kWorkerCount)
{
if (queue.TryDequeue(out var item))
foundItems.Add((int) item);
else
{
replacedert.Fail($"After adding was completed, queue was empty after popping only {foundItems.Count} items");
return;
}
}
replacedert.That(queue.IsEmpty);
Collectionreplacedert.AreEquivalent(allItems, foundItems);
}
}
19
Source : AtomicQueues.cs
with MIT License
from aksyr
with MIT License
from aksyr
[Test]
[TestCase(AllocationMode.Ephemeral)]
[TestCase(AllocationMode.Pooled)]
public void PreservesItems(AllocationMode allocationMode)
{
using (var queue = AtomicQueue<int>.Create(allocationMode))
{
var count = 0;
var items = new HashSet<int>();
var threads = new List<Thread>();
for (int i = 0; i < kWorkerCount; ++i)
{
var thread = new Thread((o) =>
{
var item = Interlocked.Increment(ref count);
queue.Enqueue((int*)item);
});
items.Add(i + 1);
thread.Start();
threads.Add(thread);
}
foreach (var thread in threads)
thread.Join();
replacedert.That(!queue.IsEmpty);
for (int i = 0; i < kWorkerCount; ++i)
{
var item = (int)queue.Dequeue();
replacedert.That(items.Contains(item), $"Missing item {item} (iteration {i})");
items.Remove(item);
}
replacedert.That(queue.IsEmpty);
replacedert.That(items.Count == 0);
}
}
19
Source : Program.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
private void Bench()
{
nums.Clear();
current = 0;
Thread[] threads = new Thread[THREADS];
var sw = Stopwatch.StartNew();
for (int i = 0;
i < THREADS;
i++) threads[i] = new Thread(Add);
for (int i = 0;
i < THREADS;
i++) threads[i].Start();
for (int i = 0;
i < THREADS;
i++) threads[i].Join();
var elapsed = sw.ElapsedMilliseconds;
bool preplaceded = true;
int last = 0;
HashSet<long> check = new HashSet<long>();
foreach (TS i in nums)
{
if (check.Contains(i.id))
{
preplaceded = false;
break;
}
check.Add(i.id);
}
Console.WriteLine($"{preplaceded}, {nums.Count}, {elapsed}ms");
resultList_.Add(elapsed);
}
19
Source : SampleMultiThreading.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
void cleanupPhysics()
{
//// Signal threads to quit.
//for (PxU32 i=0; i < gNumThreads; ++i)
for (uint i=0; i < gNumThreads; ++i)
{
//SnippetUtils::threadSignalQuit(gThreads[i].mThreadHandle);
//SnippetUtils::syncSet(gThreads[i].mWorkReadySyncHandle);
gThreads[i].quit = true;
gThreads[i].mWorkReadySyncHandle.Set();
}
//// Clean up raycast threads and syncs.
//for (PxU32 i=0; i < gNumThreads; ++i)
for (uint i=0; i < gNumThreads; ++i)
{
//SnippetUtils::threadWaitForQuit(gThreads[i].mThreadHandle);
//SnippetUtils::threadRelease(gThreads[i].mThreadHandle);
//SnippetUtils::syncRelease(gThreads[i].mWorkReadySyncHandle);
gThreads[i].mThreadHandle.Join();
gThreads[i].mWorkReadySyncHandle.Close();
}
//// Clean up the sync for the main thread.
//SnippetUtils::syncRelease(gWorkDoneSyncHandle);
gWorkDoneSyncHandle.Close();
//PX_RELEASE(gScene);
//PX_RELEASE(gDispatcher);
//PX_RELEASE(gPhysics);
//PX_RELEASE(gFoundation);
gScene.release();
gDispatcher.release();
gPhysics.release();
gFoundation.release();
//printf("SnippetMulreplacedhreading done.\n");
System.Console.WriteLine("SnippetMulreplacedhreading done.");
}
19
Source : EmulatorClientSocket.cs
with MIT License
from alanplotko
with MIT License
from alanplotko
void OnDestroy() {
shouldStop = true;
if (phoneMirroringSocket != null) {
phoneMirroringSocket.Close ();
phoneMirroringSocket = null;
}
if (phoneEventThread != null) {
phoneEventThread.Join();
}
}
19
Source : PDFExportProgress.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
public static void CloseAsync()
{
if(showThread != null && showThread.IsAlive)
{
showThread.Abort();
showThread.Join();
}
}
19
Source : ParallelRunner.cs
with Apache License 2.0
from alexyakunin
with Apache License 2.0
from alexyakunin
public TActivity[] Run()
{
foreach (var thread in Threads)
thread.Start();
foreach (var thread in Threads)
thread.Join();
return Activities;
}
19
Source : WorkerThreadPool.cs
with MIT License
from AmplifyCreations
with MIT License
from AmplifyCreations
internal void FinalizeAsyncUpdateThreads()
{
#if !NETFX_CORE && !UNITY_WEBGL
if ( !m_threadPoolFallback )
{
m_threadPoolTerminateSignal.Set();
for ( int i = 0; i < m_threadPoolSize; i++ )
{
if ( m_threadPool[ i ].IsAlive )
{
m_threadPoolContinueSignals[ i ].Set();
m_threadPool[ i ].Join();
// making sure these marked for disposal
m_threadPool[ i ] = null;
}
lock ( m_threadStateQueueLocks[ i ] )
{
while ( m_threadStateQueues[ i ].Count > 0 )
m_threadStateQueues[ i ].Dequeue().AsyncUpdate();
}
}
m_threadStateQueues = null;
m_threadStateQueueLocks = null;
m_threadPoolSize = 0;
m_threadPool = null;
m_threadPoolTerminateSignal = null;
m_threadPoolContinueSignals = null;
m_threadPoolLock = null;
m_threadPoolIndex = 0;
}
#endif
}
19
Source : ProcessReader.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public void Wait()
{
this.thread.Join();
}
19
Source : Util.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
public void stopThreads() {
if ( _background_threads==null ) { return; }
foreach (var t in _background_threads) {
if (t.IsAlive) { t.Join(); }
// Console.WriteLine($"Background Thread:{t.ManagedThreadId} joined");
}
_background_threads = null;
}
19
Source : HighResolutionTimer.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public void Stop(bool joinThread = true)
{
_isRunning = false;
// Even if _thread.Join may take time it is guaranteed that
// Elapsed event is never called overlapped with different threads
if (joinThread && Thread.CurrentThread != thread)
{
thread.Join();
}
}
19
Source : Kill.cs
with The Unlicense
from Anirban166
with The Unlicense
from Anirban166
static void Main(string[] args)
{
ThreadingClreplaced th = new ThreadingClreplaced();
Thread thread1 = new Thread(th.DoStuff);
thread1.Start();
Console.WriteLine("Press any key to exit!!!");
Console.ReadKey();
th.Stop();
thread1.Join();
}
19
Source : UndoManager.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
internal void Dispose()
{
// Not already disposed?
if(!isdisposed)
{
// Unbind any methods
General.Actions.UnbindMethods(this);
// Stop the thread and wait for it to end
backgroundthread.Interrupt();
backgroundthread.Join();
backgroundthread = null;
// Clean up
ClearUndos();
ClearRedos();
Logger.WriteLogLine("All undo and redo levels cleared.");
// Done
isdisposed = true;
}
}
19
Source : VPOManager.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public void Stop()
{
if(threads != null)
{
lock(points)
{
// Stop all threads
for(int i = 0; i < threads.Length; i++)
{
threads[i].Interrupt();
threads[i].Join();
}
threads = null;
points.Clear();
results.Clear();
}
}
}
19
Source : ScriptMode.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public void DoScriptAt(Vector2D mappos)
{
if (scriptPath == "")
{
General.Interface.DisplayStatus(StatusType.Warning,
"No Lua file selected.");
// TODO - think about if this is really the correct way to react
ChooseScript();
return;
}
if (!File.Exists(scriptPath))
{
General.Interface.DisplayStatus(StatusType.Warning,
"Can't find Lua file '" + scriptPath + "'");
ChooseScript();
return;
}
bool snaptogrid = General.Interface.ShiftState ^ General.Interface.SnapToGrid;
bool snaptonearest = General.Interface.CtrlState ^ General.Interface.AutoMerge;
stopwatch = new Stopwatch();
stopwatch.Start();
//string scriptPath = Path.Combine(General.SettingsPath, @"scripts\test.lua");
string scriptShortName = Path.GetFileName(scriptPath);
// Make undo for the draw
General.Map.UndoRedo.CreateUndo("Run script '" + scriptShortName + "'");
string replacedle = "";
if (General.Interface is MainForm)
{
replacedle = ((MainForm)General.Interface).Text;
((MainForm)General.Interface).Text = "Running Lua...";
}
General.Interface.SetCursor(Cursors.AppStarting);
General.Interface.DisplayStatus(StatusType.Busy, "Executing script '" + scriptShortName + "'!");
CancelReason = eCancelReason.Unknown;
bScriptParamsRequested = false;
bScriptSuccess = true;
bScriptDone = false;
bScriptCancelled = false;
scriptRunner = new ScriptContext(renderer, mappos, snaptogrid, snaptonearest);
scriptThread = new Thread(new ThreadStart(RunScriptThread));
scriptThread.Priority = ThreadPriority.Highest;
scriptThread.Start();
Thread.Sleep(4);
int scriptTime = 4;
while (!bScriptDone && !bScriptCancelled && scriptTime < 2800)
{
Thread.Sleep(10);
scriptTime += 10;
if (bScriptParamsRequested)
{
bScriptParamsRequested = false;
stopwatch.Stop();
returned_parameters = ScriptParamForm.ShowParamsDialog(scriptRunner.ui_parameters);
stopwatch.Start();
bScriptUIDone = true;
}
}
General.Map.IsMapBeingEdited = true;
// if our script isnt done
// let's ask the user if they wanna keep waiting
if (!bScriptDone && !bScriptCancelled)
{
General.Interface.SetCursor(Cursors.Default);
General.Interface.DisplayStatus(StatusType.Busy, "Executing script '" + scriptShortName + "', but it's being slow.");
ScriptTimeoutForm.ShowTimeout();
}
scriptThread.Join();
General.Map.IsMapBeingEdited = false;
General.Map.ThingsFilter.Update();
// Snap to map format accuracy
General.Map.Map.SnapAllToAccuracy();
// Update cached values
General.Map.Map.Update();
// Update the used textures
General.Map.Data.UpdateUsedTextures();
// Map is changed
General.Map.IsChanged = true;
General.Interface.SetCursor(Cursors.Default);
General.Interface.RedrawDisplay();
stopwatch.Stop();
// check for warnings
if (bScriptSuccess)
{
string warningsText = scriptRunner.GetWarnings();
if (warningsText.Length > 0)
{
string debugLog = scriptRunner.DebugLog;
if (debugLog.Length > 0)
{
warningsText += "\nSCRIPT DEBUG LOG:\n" + debugLog;
}
warningsText += debugLog;
if (ScriptWarningForm.AskUndo(warningsText))
{
bScriptSuccess = false;
}
}
}
// actual success
if(bScriptSuccess)
{
General.Interface.DisplayStatus(StatusType.Info,
"Lua script '" + scriptShortName + "' success in "
+ (stopwatch.Elapsed.TotalMilliseconds / 1000d).ToString("########0.00")
+ " seconds.");
string scriptLog = scriptRunner.ScriptLog;
if (scriptLog.Length > 0)
{
ScriptMessageForm.ShowMessage(scriptLog);
}
}
else
{
// okay failure
General.Map.UndoRedo.WithdrawUndo();
General.Interface.DisplayStatus(StatusType.Warning,
"Lua script '" + scriptShortName + "' failed in "
+ (stopwatch.Elapsed.TotalMilliseconds / 1000d).ToString("########0.00")
+ " seconds.");
string errorText = scriptRunner.errorText;
string warnings = scriptRunner.GetWarnings();
if (warnings.Length > 0)
{
errorText += "\nSCRIPT WARNING:\n" + warnings;
}
string scriptLog = scriptRunner.ScriptLog;
if (scriptLog.Length > 0)
{
errorText += "\nSCRIPT LOG:\n" + scriptLog;
}
string debugLog = scriptRunner.DebugLog;
if (debugLog.Length > 0)
{
errorText += "\nSCRIPT DEBUG LOG:\n" + debugLog;
}
if (errorText.Length > 0)
{
ScriptErrorForm.ShowError(errorText);
}
else
{
ScriptErrorForm.ShowError("unable to produce error message. possibly a big problem");
}
} // else error
if (General.Interface is MainForm)
{
((MainForm)General.Interface).Text = replacedle;
}
}
See More Examples