本文整理汇总了C#中System.Threading.Tasks.Task.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Task.Dispose方法的具体用法?C# Task.Dispose怎么用?C# Task.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Tasks.Task
的用法示例。
在下文中一共展示了Task.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: HandleTcpCom
public void HandleTcpCom()
{
Task readerTask = null;
Task writerTask = null;
try
{
InfoNode.ConnectionCounter++;
Console.WriteLine("{0}. Connection opened.", this._connectionIndex);
readerTask = new Task(ReadData);
writerTask = new Task(WriteData);
writerTask.Start();
readerTask.Start();
Task.WaitAll(new[] { writerTask, readerTask });
}
catch (System.IO.IOException exp)
{
Console.WriteLine("{0}. [Swallow] {1}", this._connectionIndex, exp.Message);
}
catch (AggregateException exp)
{
foreach (var exception in exp.InnerExceptions)
Console.WriteLine("{0}. [Swallow] {1}", this._connectionIndex, exception.Message);
}
catch (Exception exp)
{
Console.WriteLine("{0}. [Throw] {1}", this._connectionIndex, exp.Message);
throw;
}
finally
{
try
{
Console.WriteLine("{0}. Ending connection.", this._connectionIndex);
InfoNode.ConnectionCounter--;
if (_client != null) _client.Close();
//Make sure
Task.WaitAll(new[] { writerTask, readerTask });
readerTask.Dispose();
writerTask.Dispose();
Console.WriteLine("{0}. Connection terminated.", this._connectionIndex);
}
catch (AggregateException exp)
{
foreach(var exception in exp.InnerExceptions)
Console.WriteLine("FATAL EXCEPTION! [Throw] {0}", exception.Message);
}
catch (Exception exp)
{
Console.WriteLine("FATAL EXCEPTION! [Throw] {0}", exp.Message);
}
}
}
示例2: _GetBufferedDataFeed
static IEnumerable<DataSample> _GetBufferedDataFeed(iRacingConnection iRacingConnection, int maxBufferLength)
{
var que = new ConcurrentQueue<DataSample>();
bool cancelRequest = false;
var t = new Task(() => EnqueueSamples(que, iRacingConnection, maxBufferLength, ref cancelRequest));
t.Start();
try
{
DataSample data;
while (true)
{
if (que.TryDequeue(out data))
yield return data;
}
}
finally
{
cancelRequest = true;
t.Wait(200);
t.Dispose();
}
}
示例3: Action
public void Action(RoomItem Item, Task Task, string ExtraData)
{
if (ExtraData == "1")
{
Task.Wait(7000);
Item.FireWorkCount--;
using (DatabaseClient dbClient = GoldTree.GetDatabase().GetClient())
{
dbClient.AddParamWithValue("itemid", Item.uint_0);
dbClient.ExecuteQuery("UPDATE items SET fw_count = fw_count - 1 WHERE id = @itemid LIMIT 1");
}
}
if (Item.FireWorkCount == 0)
{
ExtraData = "0";
}
Item.ExtraData = ExtraData;
Item.UpdateState(true, true);
Task.Wait();
Task.Dispose();
}
示例4: Dispose_BeforeComplete
public static void Dispose_BeforeComplete()
{
// Verify that a task can only be disposed after it has completed
var endTask = new ManualResetEvent(false);
var task = new Task(() => { endTask.WaitOne(); });
Assert.Throws<InvalidOperationException>(() => task.Dispose());
task.Start();
Assert.Throws<InvalidOperationException>(() => task.Dispose());
endTask.Set();
task.Wait();
task.Dispose();
Assert.Throws<ObjectDisposedException>(() => { var wh = ((IAsyncResult)task).AsyncWaitHandle; });
// A task may also be disposed after it is canceled
endTask.Reset();
var cts = new CancellationTokenSource();
task = new Task(() => { endTask.WaitOne(); }, cts.Token);
cts.Cancel();
task.Dispose();
}
示例5: Dispose_ThenAddContinuation
public static void Dispose_ThenAddContinuation()
{
// Verify that a continuation can be added after a task is completed and disposed
var task = new Task(() => { });
task.Start();
task.Wait();
task.Dispose();
var task2 = task.ContinueWith(completedTask => { });
task2.Wait();
task2.Dispose();
}
示例6: SearchClick
private void SearchClick(object sender, EventArgs e)
{
try
{
_view.ClearingFields();
if(_model.SearchResultsList.Count!=0)
_model.SearchResultsList.Clear();
UpdateModel();
tokenSource = new CancellationTokenSource();
ct = tokenSource.Token;
searchingThread = Task.Factory.StartNew(() =>
{
tokenSource.Token.ThrowIfCancellationRequested();
this.MakeRegexMask();
Regex regMask = new Regex(_model.FileMask, RegexOptions.IgnoreCase);
DirectoryInfo di = new DirectoryInfo(_model.Drive);
if (!di.Exists)
throw new Exception("Выбранный Вами локальный диск не найден или Вам отказано в доступе");
_view.ShowInfoMessage("Поиск начат!");
Searching(di, regMask);
int count = _model.SearchResultsList.Count;
string endResult;
if (_model.IsResults())
endResult = String.Format("Поиск завершен. Найдено {0} файлов", count);
else
endResult = String.Format("Поиск завершен.По Вашему запросу ничего не найдено");
_view.ShowInfoMessage(endResult);
},tokenSource.Token);
}
catch(Exception ex)
{
_view.ShowErrorMessage(ex.Message);
}
finally
{
if (searchingThread.IsCanceled || searchingThread.IsCompleted || searchingThread.IsFaulted)
{
searchingThread.Dispose();
tokenSource.Dispose();
}
}
}
示例7: Work
private void Work(Task incomingTask)
{
if (StopHandle.WaitOne(0))
{
return;
}
var evt = EventLoop.NextEvent();
if (evt != null)
{
Idle = false;
_worker = incomingTask.ContinueWith(w2 => evt());
_worker.ContinueWith(Work);
} else
{
Idle = true;
}
incomingTask.Dispose();
}
示例8: Start
public void Start()
{
//bc = new List<int>();
bc = new BlockingCollection<int>();
Task Pr = new Task(producer);
Task Cn = new Task(consumer);
Pr.Start();
Cn.Start();
try
{
Task.WaitAll(Cn, Pr);
}
finally
{
Cn.Dispose();
Pr.Dispose();
}
}
示例9: Listen
private static void Listen(int port)
{
try
{
Console.WriteLine("Listening for traffic on port {0}.", port);
_tcpListener = new TcpListener(IPAddress.Any, port);
_tcpListener.Start();
while (_running)
{
var client = _tcpListener.AcceptTcpClient();
var cmn = new Communicator(client);
var tcpHandler = new Task(cmn.HandleTcpCom);
_tcpHandlers.Add(tcpHandler);
tcpHandler.Start();
}
}
catch (SocketException exp)
{
//Closing listener
Console.WriteLine("Listener. [Swallow] {0}", exp.Message);
}
catch (Exception exp)
{
Console.WriteLine("Listener. [Throw] {0}", exp.Message);
throw;
}
finally
{
foreach(var tcpHandler in _tcpHandlers)
tcpHandler.Dispose();
_tcpListener.Stop();
Console.WriteLine("Stopped listening for traffic on port {0}.", port);
}
}
示例10: TrackUploadProgress
/// <summary>
/// Tracks the upload progress in the PowerShell console.
/// </summary>
/// <param name="uploadTask">The task that tracks the upload.</param>
/// <param name="uploadProgress">The upload progress that will be displayed in the console.</param>
private void TrackUploadProgress(Task uploadTask, ProgressRecord uploadProgress,
Cmdlet commandToUpdateProgressFor, CancellationToken token)
{
// Update the UI with the progress.
var lastUpdate = DateTime.Now.Subtract(TimeSpan.FromSeconds(2));
while (!uploadTask.IsCompleted && !uploadTask.IsCanceled)
{
if (token.IsCancellationRequested)
{
// we are done tracking progress and will just break and let the task clean itself up.
try
{
uploadTask.Wait();
}
catch (OperationCanceledException)
{
if (uploadTask.IsCanceled)
{
uploadTask.Dispose();
}
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.OfType<OperationCanceledException>().Any())
{
if (uploadTask.IsCanceled)
{
uploadTask.Dispose();
}
}
else
{
throw;
}
}
break;
}
if (DateTime.Now - lastUpdate > TimeSpan.FromSeconds(1))
{
lock (ConsoleOutputLock)
{
if (commandToUpdateProgressFor != null && !token.IsCancellationRequested &&
!commandToUpdateProgressFor.Stopping)
{
commandToUpdateProgressFor.WriteProgress(uploadProgress);
}
}
}
TestMockSupport.Delay(250);
}
if (uploadTask.IsCanceled || token.IsCancellationRequested)
{
uploadProgress.RecordType = ProgressRecordType.Completed;
}
else if (uploadTask.IsFaulted && uploadTask.Exception != null)
{
// If there are errors, raise them to the user.
if (uploadTask.Exception.InnerException != null)
{
// we only go three levels deep. This is the Inception rule.
if (uploadTask.Exception.InnerException.InnerException != null)
{
throw uploadTask.Exception.InnerException.InnerException;
}
throw uploadTask.Exception.InnerException;
}
throw uploadTask.Exception;
}
else
{
// finally execution is finished, set progress state to completed.
uploadProgress.PercentComplete = 100;
uploadProgress.RecordType = ProgressRecordType.Completed;
if (commandToUpdateProgressFor != null)
{
commandToUpdateProgressFor.WriteProgress(uploadProgress);
}
}
}
示例11: ExecuteSelectImageCommand
//.........这里部分代码省略.........
while (!isComplete)
{
Thread.Sleep(250);
while (isMouseDown)
{
point = System.Windows.Forms.Cursor.Position;
Rect bounds = new Rect(new Point(topLeft.X, topLeft.Y), new Point(point.X, point.Y));
Thread.Sleep(100);
Application.Current.Dispatcher.Invoke(new Action(() =>
{
rectangle.Width = bounds.Width;
rectangle.Height = bounds.Height;
Canvas.SetTop(rectangle, bounds.Y);
Canvas.SetLeft(rectangle, bounds.X);
}));
}
}
});
canvas.Children.Add(rectangle);
window.Left = 0;
window.Top = 0;
window.Content = canvas;
window.WindowStyle = new WindowStyle();
window.ShowInTaskbar = false;
window.AllowsTransparency = true;
Bitmap screenshot = new Bitmap(1,1);
BitmapImage bitmapImage = new BitmapImage();
window.Topmost = true;
Task waitTask = new Task(() =>
{
Thread.Sleep(3000);
Application.Current.Dispatcher.Invoke(new Action(() =>
{
using (MemoryStream memory = new MemoryStream())
{
screenshot = Camera.Capture(0, ScreenCaptureMode.Screen);
screenshot.Save(memory, ImageFormat.Png);
memory.Position = 0;
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
}
window.Background = new ImageBrush(bitmapImage);
window.Show();
}));
});
task.ContinueWith(t =>
{
System.Drawing.Rectangle systemRect = new System.Drawing.Rectangle(topLeft.X, topLeft.Y,
bottomRight.X-topLeft.X, bottomRight.Y-topLeft.Y);
Bitmap tempBitmap = new Bitmap(systemRect.Width, systemRect.Height);
using (Graphics g = Graphics.FromImage(tempBitmap))
{
g.DrawImage(screenshot, new System.Drawing.Rectangle(0, 0, tempBitmap.Width, tempBitmap.Height),
systemRect, GraphicsUnit.Pixel);
}
Image = tempBitmap;
TestItem testItem = testItemController.CurrentTestItem;
OperationParameter operationParameter = testItem.Operation.GetParameterNamed("Image");
operationParameter.Value = Image;
Application.Current.Dispatcher.Invoke(new Action(() =>
{
window.Close();
Thread.Sleep(500);
testItemController.RestoreTestItemEditorWindow();
Thread.Sleep(500);
testItemController.RestoreTestItemEditorWindow();
}));
});
waitTask.Start();
waitTask.ContinueWith(t => task.Start());
window.Closed += (o, args) =>
{
doPicture = false;
task.Dispose();
};
}
示例12: _load
private void _load()
{
List<string> stream_urls = new List<string>();
Status = StreamStatus.Connecting;
// Request playlist
var gen_req = (HttpWebRequest)HttpWebRequest.Create(_channelListenM3UUrl);
gen_req.UserAgent = _userAgent;
var gen_resp = (HttpWebResponse)gen_req.GetResponse();
var gen_resp_s = gen_resp.GetResponseStream();
var gen_resp_r = new StreamReader(gen_resp_s);
stream_urls.AddRange(from url in gen_resp_r.ReadToEnd().Split('\n') where !url.TrimStart().StartsWith("#") && !string.IsNullOrEmpty(url.Trim()) select url.Trim());
// Go through each URL
foreach (string stream_url in stream_urls)
{
try
{
if (_cancel_play_token.IsCancellationRequested)
break;
// Request the stream
Console.WriteLine("Connecting to " + stream_url + "...");
var stream_req = (HttpWebRequest)HttpWebRequest.Create(stream_url);
stream_req.UserAgent = _userAgent;
stream_req.Headers.Add("icy-metadata", "1"); // Request icecast to also send metadata
stream_req.Timeout = 3000;
stream_req.ReadWriteTimeout = 5000;
var stream_resp = stream_req.GetResponse();
// Save stream info
var stream_info = new Dictionary<string, string>();
foreach (string key in stream_resp.Headers.AllKeys)
if (key.ToLower().StartsWith("ice-") || key.ToLower().StartsWith("icy-"))
{
stream_info.Add(key.ToLower(), stream_resp.Headers[key]);
Console.WriteLine(" " + key.ToLower() + ": " + stream_resp.Headers[key]);
}
StationInformation = stream_info;
// Wait for buffer to initialize properly
_buffer(stream_resp.GetResponseStream());
// Start playback
try
{
// Direct buffer for audio
_wavebuffer = new BufferedWaveProvider(_decoderMp3.OutputFormat);
_wavebuffer.BufferDuration = TimeSpan.FromSeconds(10);
// Start buffering and playback
_cancel_buffer = new CancellationTokenSource();
_cancel_buffer_token = _cancel_buffer.Token;
_bufferThread = Task.Factory.StartNew(() => _bufferLoop(), _cancel_buffer_token);
_playThread = Task.Factory.StartNew(() => _play(), _cancel_play_token);
Console.WriteLine("Load thread now sleeping, waiting until play thread finishes.");
_playThread.Wait(_cancel_buffer_token);
}
catch (OperationCanceledException)
{
{ }
}
catch (Exception error)
{
Console.WriteLine("Load thread error: {0}", error.ToString());
}
if (_playThread.Status == TaskStatus.WaitingForChildrenToComplete || _playThread.Status == TaskStatus.Running)
{
Console.WriteLine("Waiting for playback thread to exit...");
try
{
_playThread.Wait();
}
catch { { } }
_playThread.Dispose();
}
if (_bufferThread.Status == TaskStatus.WaitingForChildrenToComplete || _bufferThread.Status == TaskStatus.Running)
{
Console.WriteLine("Waiting for buffering thread to exit...");
_cancel_buffer.Cancel();
try
{
_bufferThread.Wait();
}
catch { { } }
_bufferThread.Dispose();
}
break;
}
catch (Exception error)
{
Console.WriteLine("Can't load stream: {0}", error.ToString());
}
}
Console.WriteLine("Loading thread work done.");
}
示例13: Finished
private void Finished(Task<ACommonData> data)
{
this.SwitchStopButtonStatus(false);
this._parsedItem = data.Result;
data.Dispose();
data = null;
this.LockOrUnlockInterface(false);
this._cancelGrabbingPage.Dispose();
this._cancelGrabbingPage = null;
if (this._parsedItem.IsNull() == true)
{
this.CleanLayout();
this.UpdateStatus(4);
return;
}
else if (this._parsedItem is ParsedAlbum)
{
this.UpdateStatus(3);
this.RenderAlbum((ParsedAlbum)this._parsedItem);
this.AddToLog("Данные альбома загружены");
}
else
{
this.UpdateStatus(3);
this.RenderSong((ParsedSong)this._parsedItem);
this.AddToLog("Данные песни загружены");
}
Action a = () =>
{
this.tb_InputURI.Text = this._parsedItem.ItemLink.ToString();
if (this._URI_history.Count > 0)
{
this.btn_Back.Enabled = true;
}
};
this.Invoke(a);
this._URI_history.Push(this._parsedItem.ItemLink);
}
示例14: go_data
public void go_data()
{
//запускаем заполнение списка
using (FbConnection fb = new FbConnection(fc_old.ConnectionString))
{
try
{
fb.Open();
int i_ = 0;
int j_ = tables_.Count;
foreach (string t_ in tables_)
{
i_++;
p_text = i_.ToString() + "/" + j_.ToString() + " " + t_; //прогресс таблиц
p_cur = (int)(((float)i_ / (float)j_) * 100);
using (FbTransaction ft = fb.BeginTransaction())
{
using (FbCommand fcon = new FbCommand("Select * from " + t_,fb,ft))
{
switch (t_.Trim().ToUpper())
{
case "DELETED":
fcon.CommandText += " where Date_Deleted >= cast('NOW' as date) - 180";
break;
case "ERR_LOG":
fcon.CommandText += " where id_err_log is null";
break;
case "BACKUP_LOG":
fcon.CommandText += " where id_BACKUP_LOG is null";
break;
case "SHADOWGUARD":
fcon.CommandText += " where id_SHADOW is null";
break;
case "USER_ACTIVITY":
fcon.CommandText += " where id_user_activity is null";
break;
case "MESSAGES":
fcon.CommandText += " where lastdate >= cast('NOW' as date) - 100";
break;
case "SCHEDULER":
fcon.CommandText += " where id_status is null";
break;
case "USER_CONNECTIONS":
fcon.CommandText += " where ID_USER_CONNECTIONS is null";
break;
case "REPORT_REPLICATION":
fcon.CommandText += " where DATE_CREATE >= cast('NOW' as date) - 30";
break;
}
using (FbDataReader fr = fcon.ExecuteReader())
{
while (fr.Read())
{
var sqlinsert = "insert into " + t_ + " values(";
for (int t = 0; t <= fr.FieldCount - 1; t++)
{
if (sqlinsert != "insert into " + t_ + " values(")
{
sqlinsert += ",";
}
if (fr[t] == DBNull.Value)
{
sqlinsert += "null";
}
else
{
if (fr[t].GetType().ToString().ToUpper() == "SYSTEM.DOUBLE")
{
sqlinsert += fr[t].ToString().Replace(",", ".");
}
else
//заменяем все ' на ''
sqlinsert += "'" + fr[t].ToString().Replace("'", "''").Replace(" 0:00:00", " ") + "'";
}
}
sqlinsert += ");";
q_data.Enqueue(sqlinsert);//добавляем INSERT
if (q_data.Count >= 100000)
{
//запускаем создание записей на базе
using (Task t_load = new Task(go_load))
{
t_load.Start();
t_load.Wait();
t_load.Dispose();
q_data.Clear();
}
}
}
fr.Dispose();
}
fcon.Dispose();
}
ft.Commit();
ft.Dispose();
}
}
//и в конце запустим еще раз
//.........这里部分代码省略.........
示例15: StartLoad
//second thread
private void StartLoad()
{
flag = "checkFiles";
InvokeUpdateControls();
task = Task.Factory.StartNew(CheckFiles);
task.Wait();
task.Dispose();
flag = "checkConn";
InvokeUpdateControls();
task = Task.Factory.StartNew(CheckConnection);
task.Wait();
//task.Dispose();
flag = "fetchSettings";
InvokeUpdateControls();
task = Task.Factory.StartNew(FetchSettings);
task.Wait();
task.Dispose();
flag = "checkUpdate";
InvokeUpdateControls();
task = Task.Factory.StartNew(CheckUpdates);
task.Wait();
task.Dispose();
flag = "fetchBulletin";
InvokeUpdateControls();
task = Task.Factory.StartNew(FetchBulletin);
task.Wait();
task.Dispose();
flag = "success";
InvokeUpdateControls();
task = Task.Factory.StartNew(Finish);
task.Wait();
task.Dispose();
}