我正在创建一个应用程序,它从一个位置抓取RSSFeed,解析它,并在丰富的ListView中显示这些项目.我已经让它同步工作,但它挂起初始下载.我使用Google博客中的ImageDownloader异步抓取图像来填充ListView,但是我如何进行线程下载过程,使显示更新等到完成后再将RSS传递给适配器,并在初始化期间显示对话框下载?我对线程和消息处理完全不熟悉!
到目前为止,这是我的onCreate中的代码:
feedWait = new Handler() {
public void handleMessage(Message msg) {
Log.d(TAG, "made it to handler");
UpdateDisplay();
}
};
netThread.start();
Run Code Online (Sandbox Code Playgroud)
这是线程:
private Thread netThread = new Thread() {
public void run() {
getFeed();
feedWait.handleMessage(new Message());
}
};
Run Code Online (Sandbox Code Playgroud)
这会抛出一个错误,说我必须在创建一个处理程序之前调用Looper.prepare(),但如果我在onCreate中执行Looper.prepare(),它就会失败.
我需要为我的应用程序创建一个单独的线程来记录一些事情,并建议我使用Task.
我似乎没有这个权利,因为我不完全理解任务(我猜).
这是我有的:
public static void LogException(string message, Exception ex)
{
Action action= delegate() { logException(message, ex); };
new Task(action);
}
public static void logException(string message, Exception ex)
{
var stackTrace = new StackTrace();
var origin = stackTrace.GetFrame(1).GetMethod().Name;
var originclass = stackTrace.GetFrame(1).GetMethod().ReflectedType.Name;
var neworigin = string.Format("{0}.{1}", originclass, origin);
message += Environment.NewLine + Environment.NewLine + GetFullExceptionMessage(ex);
if (string.IsNullOrEmpty(message)) message = "No message given";
//var exceptions = GetAllErrMessages(ex);
//message = exceptions.Aggregate(message, (current, exception) => current + Environment.NewLine + exception);
EventLogging.LogEvent(neworigin, message, EventLogEntryType.Error, …Run Code Online (Sandbox Code Playgroud) 我正在创建一个聊天程序,其中包含我在新版JavaFx场景构建器中创建的GUI.我有一个扩展应用程序的main方法,我有一个simpleController(控制所有按钮,标签,anchorPanes等)在我的GUI中.
除此之外,我有一个可以接收和发送消息的服务器应用程序.为此,我创建了以下简单协议:
命令/描述:
使用这个简单的逻辑,我可以很容易地让用户连接,聊天和断开连接.然而,事实证明,应该是一项简单的任务已成为我最糟糕的噩梦.
到目前为止,我的用户连接到程序没有问题,更多的用户可以同时连接.
事情开始变得棘手的是当我想在服务器和客户端之间发送和接收消息时.
我不知道在使用线程时如何更新GUI.我试图阅读Task类,但我无法看到是否应该使用它而不是线程,或者线程应该将此作为参数.
我应该创建一个侦听输入并使该类扩展线程的新类吗? 或者
线程是否应该在我的simpleController类中运行?
主要
public class Main extends Application{
public static void main(String[] args) throws IOException{
Application.launch(Main.class, (java.lang.String[]) null);
}
@Override
public void start(Stage primaryStage) throws Exception {
try {
AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("testingBackground.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Chatten");
primaryStage.show();
} catch (Exception ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log( …Run Code Online (Sandbox Code Playgroud) 我想在列表框中添加一些文本Task,我只需使用一个按钮并在点击事件中放置此代码:
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
listBox1.Items.Add("Number cities in problem = " + i.ToString());
System.Threading.Thread.Sleep(1000);
}
}, CancellationToken.None, TaskCreationOptions.None, uiScheduler);
Run Code Online (Sandbox Code Playgroud)
但是直到for循环结束它才能工作并且UI被锁定.
问题出在哪儿 ?
谢谢 :)
我正在尝试做类似光纤的代码,我可以进入任务并摆脱它.我试过的代码:
class TaskActivity {
CancellationTokenSource _m=new CancellationTokenSource( int.MaxValue )
,_t=new CancellationTokenSource( int.MaxValue );
public async Task PauseTask( ) { //call and await it when I want to pause task inside itself
_m.Cancel( );
_t = new CancellationTokenSource( int.MaxValue );
while( !_t.IsCancellationRequested )
await Task.Yield( );
}
public async Task ResumeTask( ) { //call and wait for it when I want to resume a task from the main context
_t.Cancel( );
_m = new CancellationTokenSource( int.MaxValue );
while( !_m.IsCancellationRequested )
await …Run Code Online (Sandbox Code Playgroud) 假设我有一个简单的C#控制台应用程序:
class Program
{
static async void func()
{
Thread.CurrentThread.Name = "main";
await Task.Run(() =>
{
Thread.CurrentThread.Name = "child";
Thread.Sleep(5000);
});
Console.WriteLine("continuation is running on {0} thread", Thread.CurrentThread.Name);
}
static void Main(string[] args)
{
func();
Thread.Sleep(10000);
}
}
Run Code Online (Sandbox Code Playgroud)
当5000毫秒通过时,我们看到"继续在子线程上运行"消息.当另一个5000毫秒通过时,主线程完成其工作并关闭应用程序.它看起来很合乎逻辑:异步任务及其延续在同一子线程上运行.
但现在假设我有一个简单的WPF应用程序:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
async private void mainWnd_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Thread.CurrentThread.Name = "main";
await Task.Run(() =>
{
Thread.CurrentThread.Name = "child";
Thread.Sleep(5000);
});
this.Title = string.Format("continuation is …Run Code Online (Sandbox Code Playgroud) 我知道Task.WaitAll(Task1,Task2)等待所有提供的Task对象完成执行.
什么是Task.WhenAll用于什么?
创建将在所有提供的任务完成后完成的任务.
什么是真实世界场景,曾经可以应用Task.WhenAll()
我正在尝试使用OLE DB COMMAND在SSIS中进行此更新:
UPDATE
TABLE_A
SET
COLUMN_C = CONCAT(?,' ',?)
FROM
TABLE_A INNER JOIN TABLE_B ON
TABLE_A.ID = TABLE_B.ID
Run Code Online (Sandbox Code Playgroud)
但是当我尝试映射参数时,我收到此消息:
“无法推导出参数类型,因为单个表达式包含两个未键入的参数”
我不知道此查询是否做错了什么,或者是否不可能在一个句子中使用多个参数。
我正在使用VS 2010
我有一个关于使用cancellationToken和cancellationTokenSource取消任务的问题:
通常的方法如下:
var cts = new CancellationTokenSource();
var t = Task.Run(() => {
while(true)
{
if (!cts.IsCancellationRequested)
{ //do stuff }
}
}, cts.Token);
Run Code Online (Sandbox Code Playgroud)
因此,while循环一直持续到请求令牌为止.今天,在研究Cancel()方法时,我发现你可以使用 Register()方法来定义在请求令牌时运行的其他代码,所以我想知道,如果有人写了这样的话:
var cts = new CancellationTokenSouce();
token=cts.Token;
token.Register(
() => {
//do something to manage the cancel call
return;
};
)
var t = Task.Run(() => {
//do stuff
}, cts.Token);
Run Code Online (Sandbox Code Playgroud)
通过这样做,与该关联的任务CancellationToken将立即停止执行,而不是像在通常的实现中那样必须完成当前的迭代.我的问题是:这是立即停止Task或有更好方法的正确方法吗?
我需要运行任务以检查连接。
在此检查期间,不应冻结我的窗户。
因此,我启动了任务,并在此任务结束时关闭了窗口。
但这会返回一个异常:InvalidOperationException:“调用线程无法访问该对象,因为另一个线程拥有它”。
像这样 :
private void Window_ContentRendered(object sender, System.EventArgs e)
{
Task.Run(() =>
{
ConnectionState = false;
if (NetworkTools.CheckGlobalConnection() == (ConnectionStatus.NetworkConnectionSuccess, ConnectionStatus.ServerConnectionSuccess))
{
ConnectionState = true;
}
this.Close();
});
}
Run Code Online (Sandbox Code Playgroud)
如何在任务结束时关闭窗口而不冻结它且没有此异常?(我有一个无限旋转的进度条)
task ×10
c# ×7
asynchronous ×2
wpf ×2
.net ×1
action ×1
android ×1
async-await ×1
c#-4.0 ×1
cancellation ×1
delegates ×1
freeze ×1
java ×1
javafx ×1
parameters ×1
rss ×1
sql ×1
ssis ×1